让我们说我有两个熊猫DataFrame,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 |
答案 0 :(得分:2)
将get_dummies
与max
一起使用,然后join
并仅对df22
中的列替换缺失值:
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 False