【问题标题】:Unable to allocate GiB - pandas get_dummies on multiple columns无法在多个列上分配 GiB - pandas get_dummies
【发布时间】: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='')

其次,我总结了引用相同颜色的列;结果将是10。这是使用我的原始数据框中断或运行数天的代码:

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


    【解决方案1】:

    使用:

    columns = ['trial1', 'trial2', 'trial3', 'trial4', 'trial5']
    df1 = df.melt('item').loc[lambda x: x['value'].ne('')]
    oneHot = pd.crosstab(df1['item'], df1['value']).gt(0).astype(int)
    print (oneHot)
    value  black  blue  gray  green  red
    item                                
    a          1     1     1      1    1
    b          0     1     0      1    0
    c          0     0     0      0    1
    d          0     1     0      0    0
    e          0     1     0      0    0
    f          0     1     1      1    1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-21
      • 2016-09-19
      • 2014-07-29
      • 2014-01-16
      • 1970-01-01
      • 2021-08-11
      相关资源
      最近更新 更多