【发布时间】:2023-02-21 20:41:29
【问题描述】:
以下代码有效,但由于Pandas unable to allocate GiB for an array with shape X and data type Y,它在应用于我的数据框时中断。我试图用 dask.dataframe 解决问题,但也没有用。我希望我的代码可以改进。也许这里的任何人都知道怎么做。
它以类似于以下内容的数据框开始:
import pandas as pd
data = {'item':['a', 'b', 'c', 'd', 'e', 'f'],
'trial1':['blue', 'green', 'red', 'blue', 'blue', 'green'],
'trial2':['green', 'blue', '', '', '', 'red'],
'trial3':['red', '', '', '', '', 'blue'],
'trial4':['gray', '', '', '', '', 'gray'],
'trial5':['black','', '', '', '', '']}
df = pd.DataFrame(data)
df
item trial1 trial2 trial3 trial4 trial5
0 a blue green red gray black
1 b green blue
2 c red
3 d blue
4 e blue
5 f green red blue gray
请注意,每种颜色对于每个项目只出现一次,也就是说,trial1 .. trial5 列中的一行中没有重复的单元格。 (原始数据框有 10 个试验、300000 个项目和 30000 个独特的“颜色”)。我希望每件商品都针对其独特的颜色进行一次性编码。首先,我为每个试验计算单热编码:
columns = ['trial1', 'trial2', 'trial3', 'trial4', 'trial5']
oneHot = pd.get_dummies(df[columns], sparse=True, prefix='', prefix_sep='')
其次,我总结了引用相同颜色的列;结果将是1 或0。这是使用我的原始数据框中断或运行数天的代码:
oneHotAgg = oneHot.groupby(oneHot.columns, axis=1).sum()
oneHotAgg = oneHotAgg.iloc[:, 1:] # don't know why this column without name is added; just delete it
第三,我再次将 one-hot 编码与项目结合起来:
result = pd.concat([df.item, oneHotAgg], axis=1)
生成的数据框如下所示:
item black blue gray green red
0 a 1 1 1 1 1
1 b 0 1 0 1 0
2 c 0 0 0 0 1
3 d 0 1 0 0 0
4 e 0 1 0 0 0
5 f 0 1 1 1 1
这个问题还有其他解决方案吗?特别是更有效的解决方案?欢迎任何建议!!!
附言有一些解决方案可用于我的问题,我的代码基于这些解决方案。特别是这个questions 非常有帮助。请注意对 BENY 提出的解决方案的评论(已接受的答案)。
【问题讨论】:
标签: python pandas group-by sum one-hot-encoding