【发布时间】:2016-05-26 10:48:07
【问题描述】:
我有一个 10e6 行和 10e3 列的 scipy 稀疏矩阵,填充为 1%。我还有一个大小为 10e6 的数组,其中包含与我的稀疏矩阵的 10e6 行相对应的键。我想按照这些键对稀疏矩阵进行分组,并使用求和函数进行聚合。
例子:
Keys:
['foo','bar','foo','baz','baz','bar']
Sparse matrix:
(0,1) 3 -> corresponds to the first 'foo' key
(0,10) 4 -> corresponds to the first 'bar' key
(2,1) 1 -> corresponds to the second 'foo' key
(1,3) 2 -> corresponds to the first 'baz' key
(2,3) 10 -> corresponds to the second 'baz' key
(2,4) 1 -> corresponds to the second 'bar' key
Expected result:
{
'foo': {1: 4}, -> 4 = 3 + 1
'bar': {4: 1, 10: 4},
'baz': {3: 12} -> 12 = 2 + 10
}
什么是更有效的方法?
我已经尝试在我的稀疏矩阵上使用 pandas.SparseSeries.from_coo 以便能够使用 pandas group by,但我得到了这个已知的错误:
site-packages/pandas/tools/merge.py in __init__(self, objs, axis, join, join_axes, keys, levels, names, ignore_index, verify_integrity, copy)
863 for obj in objs:
864 if not isinstance(obj, NDFrame):
--> 865 raise TypeError("cannot concatenate a non-NDFrame object")
866
867 # consolidate
TypeError: cannot concatenate a non-NDFrame object
【问题讨论】:
-
对于矩阵中的每个非零元素,
keys列表中是否有一个元素?如前所述,这个问题看起来更像是一个列表和字典(dok格式稀疏?)问题,而不是数组/矩阵问题。
标签: python pandas group-by scipy sparse-matrix