微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – 根据列的值将列转换为多个列

Python中,我想知道是否有办法从这里转换单列数据帧:

enter image description here


进入这个:

enter image description here

解决方法:

来源DF:

In [204]: df
Out[204]:
     Country
0      Italy
1  Indonesia
2     Canada
3      Italy

我们可以使用pd.get_dummies()

In [205]: pd.get_dummies(df.Country)
Out[205]:
   Canada  Indonesia  Italy
0       0          0      1
1       0          1      0
2       1          0      0
3       0          0      1

sklearn.feature_extraction.text.CountVectorizer

In [211]: from sklearn.feature_extraction.text import CountVectorizer

In [212]: cv = CountVectorizer()

In [213]: r = pd.SparseDataFrame(cv.fit_transform(df.Country), 
                                 columns=cv.get_feature_names(), 
                                 index=df.index,
                                 default_fill_value=0)

In [214]: r
Out[214]:
   canada  indonesia  italy
0       0          0      1
1       0          1      0
2       1          0      0
3       0          0      1

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐