python - 虚拟代码具有相同名称的多个列,包括数据中不存在的类别
问题描述
附加问题
这些列需要使用具有以下格式的字典将实际问题附加到每个列名的开头。它需要以矢量化的方式访问,因为有很多这些列/列表。
字典
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)
解决方案
两件事,因为你有重复的列名,你可以循环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)
推荐阅读
- javascript - Jquery 对话框上的关闭按钮
- python - 将列重新排列到熊猫中的下一行
- java - 如何在给定字符串中获取 \" 字符串的正则表达式
- sql - 尝试在 SQL 中插入多行时出现语法错误?
- c# - 如何仅在当前页面顶部/覆盖当前页面上显示 ProgressRing 控件?
- vue.js - VueJs CLI 3 - 如何添加外部库
- java - Hibernate 在整个 Spring Boot 应用程序上设置属性访问策略
- java - Java Base64.getDecoder().decode() c# 等效
- solr - Solr 数据导入 12/12 已获取但 0/12 已处理
- python-3.x - py2app 捆绑系统 MacOSX python 2.7 而不是 python 3