Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transforming a Column into Multiple Columns according to Their Values

In Python, I am wondering if there is a way to transform a one-column dataframe from this: enter image description here

into this:

enter image description here

like image 755
Fxs7576 Avatar asked Dec 12 '25 07:12

Fxs7576


1 Answers

Source DF:

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

we can use 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

Or 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
like image 57
MaxU - stop WAR against UA Avatar answered Dec 13 '25 21:12

MaxU - stop WAR against UA