首页 > 解决方案 > 虚拟代码具有相同名称的多个列,包括数据中不存在的类别

问题描述

附加问题

这些列需要使用具有以下格式的字典将实际问题附加到每个列名的开头。它需要以矢量化的方式访问,因为有很多这些列/列表。

字典

dic = dict({'ab': 'what colour is this?',
     'cd': 'what size is this?',
     'ef': 'who do you live with?'})

代码

dout=[]
for c in df.columns[1:].unique(): #here unique
    b = (pd.get_dummies(df[c], prefix='', prefix_sep='')
           .sum(axis=1, level=0) #here equivalent to groupby.sum
           .reindex(columns = all_categories[c], fill_value=0))
        
    b.columns = [c + ' ' + str(col) for col in b.columns]
    
    for key, value in dic.items():
        b.columns = [col.replace(c, value) for col in b.columns]
        
    dout.append(b)
    


感谢@ben.T,以下部分已解决

我有一个我想要虚拟代码的数据框 - 有多个具有相同名称的列,并且我还想在虚拟编码数据框中包含所有可能的类别,这些类别不一定存在于实际数据框本身中。

我可以让它工作,直到我尝试合并不存在的答案中的列 - 我不断收到错误ValueError: cannot reindex from a duplicate axis

下面是一些类似的数据,还有我的小代码(a有效,b无效)

非常感谢!

create some data

all_categories = {'ab':  ['green', 'red', 'blue', 'pink', 'None', 
    'orange', 'purple, white'],
                  'cd':  ['XS', 'M', 'L', 'XL'],
                  'ef':  ['husband', 'wife', 'son', 'daughter',
    'grandparent', 'aunt', 'uncle','None'] }

data = {'ab':  ['green', 'red', 'blue', 'None'],
        'ab1': ['red', 'yellow', 'None', 'None'],
        'cd': ['L', 'XL', 'M','L'],
        'ef':['husband', 'wife', 'husband', 'None'],
        'ef1':['son', 'grandparent', 'son', 'None'],
        'ef2':['None', 'son', 'None', 'None'] }

df = pd.DataFrame(data, columns = ['ab', 'ab1', 'cd', 'ef', 'ef1', 'ef2'])
df = df.rename(columns={'ab1':'ab', 'ef1':'ef', 'ef2':'ef'})

command

dout=[]
for c in df.columns[1:]:
    a = pd.concat([df['id'], pd.get_dummies(df[c], prefix='', prefix_sep='')],axis=1) ### this works  
    b = pd.get_dummies(df[c], prefix='', prefix_sep='').reindex(columns = all_categories, fill_value=0) ### this does not work 
    dout.append(b)

标签: pythonpandasindexingdummy-variable

解决方案


两件事,因为你有重复的列名,你可以循环unique列名。对于 的问题reindex,可以先使用sum沿列(axis=1),再使用 level=0 来执行 groupby 相似的列名。

dout=[]
for c in df.columns[1:].unique(): #here unique
    b = (pd.get_dummies(df[c], prefix='', prefix_sep='')
           .sum(axis=1, level=0) #here equivalent to groupby.sum
           .reindex(columns = all_categories[c], fill_value=0)
        )
    dout.append(b)

推荐阅读