根据其值将一列转换为多列 [英] Transforming a Column into Multiple Columns according to Their Values
本文介绍了根据其值将一列转换为多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中,我想知道是否有一种方法可以从中转换单列数据框:
In Python, I am wondering if there is a way to transform a one-column dataframe from this:
对此:
推荐答案
来源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
这篇关于根据其值将一列转换为多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文