MCPcopy
hub / github.com/pandas-dev/pandas / to_coo

Method to_coo

pandas/core/arrays/sparse/accessor.py:396–446  ·  view source on GitHub ↗

Return the contents of the frame as a sparse SciPy COO matrix. Returns ------- scipy.sparse.spmatrix If the caller is heterogeneous and contains booleans or objects, the result will be of dtype=object. See Notes. See Also ---

(self)

Source from the content-addressed store, hash-verified

394 )
395
396 def to_coo(self) -> spmatrix:
397 """
398 Return the contents of the frame as a sparse SciPy COO matrix.
399
400 Returns
401 -------
402 scipy.sparse.spmatrix
403 If the caller is heterogeneous and contains booleans or objects,
404 the result will be of dtype=object. See Notes.
405
406 See Also
407 --------
408 DataFrame.sparse.to_dense : Convert a DataFrame with sparse values to dense.
409
410 Notes
411 -----
412 The dtype will be the lowest-common-denominator type (implicit
413 upcasting); that is to say if the dtypes (even of numeric types)
414 are mixed, the one that accommodates all will be chosen.
415
416 e.g. If the dtypes are float16 and float32, dtype will be upcast to
417 float32. By numpy.find_common_type convention, mixing int64 and
418 and uint64 will result in a float64 dtype.
419
420 Examples
421 --------
422 >>> df = pd.DataFrame({"A": pd.arrays.SparseArray([0, 1, 0, 1])})
423 >>> df.sparse.to_coo()
424 <COOrdinate sparse matrix of dtype 'int64'
425 with 2 stored elements and shape (4, 1)>
426 """
427 import_optional_dependency("scipy")
428 from scipy.sparse import coo_matrix
429
430 dtype = find_common_type(self._parent.dtypes.to_list())
431 if isinstance(dtype, SparseDtype):
432 dtype = dtype.subtype
433
434 cols, rows, data = [], [], []
435 for col, (_, ser) in enumerate(self._parent.items()):
436 sp_arr = ser.array
437
438 row = sp_arr.sp_index.indices
439 cols.append(np.repeat(col, len(row)))
440 rows.append(row)
441 data.append(sp_arr.sp_values.astype(dtype, copy=False))
442
443 cols_arr = np.concatenate(cols)
444 rows_arr = np.concatenate(rows)
445 data_arr = np.concatenate(data)
446 return coo_matrix((data_arr, (rows_arr, cols_arr)), shape=self._parent.shape)
447
448 @property
449 def density(self) -> float:

Callers

nothing calls this directly

Calls 6

find_common_typeFunction · 0.90
itemsMethod · 0.45
appendMethod · 0.45
repeatMethod · 0.45
astypeMethod · 0.45

Tested by

no test coverage detected