我在寻找一个更好的方式来创建一个从pandas dataframe一个scipy sparse matrix。如何从熊猫数据框创建一个scipy稀疏矩阵?
这里是我目前有
row = []; column = []; values = []
for each row of the dataframe
for each column of the row
add the row_id to row
add the column_id to column
add the value to values
sparse_matrix = sparse.coo_matrix((values, (row, column), shape=(max(row)+1,max(column)+1))
但是我个人认为会有一个更好的方式来做事的伪代码。几乎什么工作是以下
dataframe.unstack().to_sparse().to_coo()
不过,这回我三(稀疏矩阵,列ID和行ID)的。问题是我需要行ID实际上是稀疏矩阵的一部分。
下面是一个完整的例子。我有一个数据帧,看起来像如下
instructor_id primary_department_id
id
4109 2093 129
6633 2093 129
6634 2094 129
6635 2095 129
如果我做我上面提到的操作,我得到
ipdb> data = dataframe.unstack().to_sparse().to_coo()[0]
ipdb> data
<2x4 sparse matrix of type '<type 'numpy.int64'>'
with 8 stored elements in COOrdinate format>
ipdb> print data
(0, 0) 2093
(0, 1) 2093
(0, 2) 2094
(0, 3) 2095
(1, 0) 129
(1, 1) 129
(1, 2) 129
(1, 3) 129
但我需要
ipdb> print data
(4109, 0) 2093
(6633, 0) 2093
(6634, 0) 2094
etc.
我愿意使用任何额外库或依赖项。
似乎有一个question that asks for the reverse operation,但我还没有找到此操作的解决方案。
“问题是我需要行ID实际上是稀疏矩阵的一部分” - 你能否明白你的意思是什么? –
完整的工作示例程序可以帮助用硬编码的输入数据。我不确定为什么你想把一个完整的,密集的DataFrame变成一个稀疏矩阵 - 你确定要这么做吗?为什么? –
你看过稀疏的熊猫版吗?最近有几个关于在scipy和sparse之间来回切换的问题。 http://pandas.pydata.org/pandas-docs/stable/sparse.html – hpaulj