[英]Pivot string column in Pandas
I am new to pandas and I have below data我是 pandas 的新手,我有以下数据
Country Skills
0 India Finance
1 UK Law
2 US Computer
I am trying to convert this to我正在尝试将其转换为
India UK US Skills
0 Y N N Finance
1 N Y N Law
2 N N Y Computer
Can anyone help?任何人都可以帮忙吗?
>>> import pandas as pd
>>> df = pd.read_clipboard()
>>> df
Country Skills
0 India Finance
1 UK Law
2 US Computer
>>> dummies = pd.get_dummies(df['Country'])
>>> dummies
India UK US
0 1 0 0
1 0 1 0
2 0 0 1
>>> result = pd.concat([dummies, df], axis=1)
>>> result
India UK US Country Skills
0 1 0 0 India Finance
1 0 1 0 UK Law
2 0 0 1 US Computer
>>> result = result.drop('Country', axis=1)
>>> result
India UK US Skills
0 1 0 0 Finance
1 0 1 0 Law
2 0 0 1 Computer
>>> result = result.replace({1:'Y', 0:'N'})
>>> result
India UK US Skills
0 Y N N Finance
1 N Y N Law
2 N N Y Computer
One line一条线
pd.concat([dummies, df], axis=1).drop('Country', axis=1).replace({1:'Y', 0:'N'})
India UK US Skills
0 Y N N Finance
1 N Y N Law
2 N N Y Computer
Try -尝试 -
df = pd.concat([pd.get_dummies(df['Country']),df['Skills']],axis=1).replace({1:'Y', 0:'N'})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.