假设我有两只熊猫DataFrames,df1和df2,一只包含人的名字和年龄,另一只详细说明它们正在研究的内容。怎样才能有效地将两者结合起来,这样我就有了每个人都在学习的布尔字段?
例如,考虑到以下情况
# df1
name | age
------|----
John | 24
Kelly | 49
Gemma | 18
Bob | 29
# df2
name | studies
------|----------
John | education
John | science
Kelly | science
Bob | law
Bob | commerce如何为每个研究领域创建具有布尔值的下列数据?
name | age | education | science | law | commerce |
------|-----|-----------|---------|-------|----------|
John | 24 | True | True | False | False |
Kelly | 49 | False | True | False | False |
Gemma | 18 | False | False | False | False |
Bob | 29 | False | False | True | True |发布于 2018-09-24 08:56:27
将get_dummies与max一起使用,然后只为df22中的列替换缺少的值join和替换
s = df2.set_index('name')['studies']
df22 = pd.get_dummies(s, prefix_sep='', prefix='', dtype=bool).max(level=0)
df = df1.join(df22, on='name').fillna(dict.fromkeys(df22.columns, False))
print (df)
name age commerce education law science
0 John 24 False True False True
1 Kelly 49 False False False True
2 Gemma 18 False False False False
3 Bob 29 True False True Falsehttps://stackoverflow.com/questions/52475658
复制相似问题