gpt4 book ai didi

python - 如何将 Pandas 组变成 SparseDataFrame

转载 作者:行者123 更新时间:2023-11-30 23:29:47 24 4
gpt4 key购买 nike

我有一个很高的(2743470 行,2 列)DataFrame,将其称为 df,具有以下列,整数索引:

| item | user |
| 1 | abc |
| 15 | abc |
| 3 | def |

我知道总共有 35605 个可能的项目 ID 和 53690 个用户。我想要做的是将其转换为 SparseDataFrame,每行代表一个用户,一列代表一个项目,只要用户与原始表中的项目相关联,该值就是 1。

我尝试过进行分组,但那时我不知道如何对其余部分进行矢量化。我得到的最好的如下:

ids = pandas.Index(df.item.drop_duplicates())
g = df.groupby('user')
arr = []
arr_i = []
for name, group in g:
arr_i.append(name)
s = pandas.Series({val: 1 for val in group.item}, index=ids).to_sparse()
arr.append(s)
book_reads = pandas.SparseDataFrame(arr, index=arr_i)

但即使这样也会失败:

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

我尝试将索引参数取出到 SparseDataFrame 或将其设置为一组整数而不是字符串,但无济于事。唯一有效的方法是先创建一个常规 DataFrame,然后对其调用 to_sparse,但这会占用太多内存。

有没有办法在仅使用稀疏数据结构的情况下向量化此操作?

更新

我还尝试过伪造全 1 的值列并进行旋转,但几乎立即出现内存错误,可能是因为旋转产生了密集的 DataFrame。

最佳答案

我认为您不会遇到内存问题,因为最终结果不会那么大(因此 unstack 不会爆炸)

In [14]: df.groupby('user')['item'].apply(lambda x: Series(1,index=x)).unstack()
Out[14]:
1 3 15
user
abc 1 NaN 1
def NaN 1 NaN

[2 rows x 3 columns]

关于python - 如何将 Pandas 组变成 SparseDataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20976736/

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