gpt4 book ai didi

python - 在 pandas 中有效地创建稀疏数据透视表?

转载 作者:IT老高 更新时间:2023-10-28 20:31:51 28 4
gpt4 key购买 nike

我正在将包含两列(A 和 B)的记录列表转换为矩阵表示。我一直在 pandas 中使用 pivot 函数,但结果却相当大。 pandas 是否支持旋转为稀疏格式?我知道我可以旋转它,然后将其转换为某种稀疏表示,但并不像我想要的那样优雅。我的最终目标是将其用作预测模型的输入。

或者,在 pandas 之外是否有某种稀疏枢轴功能?

编辑:这里是一个非稀疏枢轴的例子

import pandas as pd
frame=pd.DataFrame()
frame['person']=['me','you','him','you','him','me']
frame['thing']=['a','a','b','c','d','d']
frame['count']=[1,1,1,1,1,1]

frame

person thing count
0 me a 1
1 you a 1
2 him b 1
3 you c 1
4 him d 1
5 me d 1

frame.pivot('person','thing')

count
thing a b c d
person
him NaN 1 NaN 1
me 1 NaN NaN 1
you 1 NaN 1 NaN

这创建了一个矩阵,可以包含人和事物的所有可能组合,但它不是稀疏的。

http://docs.scipy.org/doc/scipy/reference/sparse.html

稀疏矩阵占用的空间更少,因为它们可以暗示诸如 NaN 或 0 之类的东西。如果我有一个非常大的数据集,这个旋转函数可以生成一个由于大量 NaN 或 0 而应该是稀疏的矩阵。我希望我可以通过立即生成稀疏的东西而不是创建密集矩阵然后将其转换为稀疏矩阵来节省大量空间/内存。

最佳答案

这是一种基于人和事物的数据和索引创建稀疏 scipy 矩阵的方法。 person_uthing_u 是代表您要创建的数据透视的行和列的唯一条目的列表。注意:这假设您的计数列中已经包含您想要的值。

from scipy.sparse import csr_matrix

person_u = list(sort(frame.person.unique()))
thing_u = list(sort(frame.thing.unique()))

data = frame['count'].tolist()
row = frame.person.astype('category', categories=person_u).cat.codes
col = frame.thing.astype('category', categories=thing_u).cat.codes
sparse_matrix = csr_matrix((data, (row, col)), shape=(len(person_u), len(thing_u)))

>>> sparse_matrix
<3x4 sparse matrix of type '<type 'numpy.int64'>'
with 6 stored elements in Compressed Sparse Row format>

>>> sparse_matrix.todense()

matrix([[0, 1, 0, 1],
[1, 0, 0, 1],
[1, 0, 1, 0]])

根据您的原始问题,scipy 稀疏矩阵应该足以满足您的需求,但如果您希望拥有一个稀疏数据框,您可以执行以下操作:

dfs=pd.SparseDataFrame([ pd.SparseSeries(sparse_matrix[i].toarray().ravel(), fill_value=0) 
for i in np.arange(sparse_matrix.shape[0]) ], index=person_u, columns=thing_u, default_fill_value=0)

>>> dfs
a b c d
him 0 1 0 1
me 1 0 0 1
you 1 0 1 0

>>> type(dfs)
pandas.sparse.frame.SparseDataFrame

关于python - 在 pandas 中有效地创建稀疏数据透视表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31661604/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com