Pandas 0.20.0+:
Ab Pandas Version 0.20.0, den 5. Mai veröffentlicht 2017, ist es ein Einzeiler dafür:
from scipy import sparse
def sparse_df_to_csr(df):
return sparse.csr_matrix(df.to_coo())
Dies nutzt die neu to_coo()
method.
früheren Versionen:
Aufbauend auf Victor Mays Antwort, hier ist eine etwas schnellere Implementierung, aber es funktioniert nur, wenn die gesamte SparseDataFrame
mit allen BlockIndex
(Anmerkung spärlich ist: wenn es mit get_dummies
erstellt wurde, das wird die Fall).
Bearbeiten: Ich habe dies geändert, so dass es mit einem Füllwert ungleich Null arbeiten wird. CSR hat keinen nativen Nicht-Null-Füllwert, daher müssen Sie ihn extern aufzeichnen.
import numpy as np
import pandas as pd
from scipy import sparse
def sparse_BlockIndex_df_to_csr(df):
columns=df.columns
zipped_data = zip(*[(df[col].sp_values - df[col].fill_value,
df[col].sp_index.to_int_index().indices)
for col in columns])
data, rows=map(list, zipped_data)
cols=[np.ones_like(a)*i for (i,a) in enumerate(data)]
data_f = np.concatenate(data)
rows_f = np.concatenate(rows)
cols_f = np.concatenate(cols)
arr = sparse.coo_matrix((data_f, (rows_f, cols_f)),
df.shape, dtype=np.float64)
return arr.tocsr()
dies Run umgekehrt? http://StackOverflow.com/questions/17818783/populate-a-pandas-sparsedataframe-from-a-scipy-sparse-matrix – JohnE