python - Transforming a Column into Multiple Columns according to Their Values -


in python, wondering if there way transform one-column dataframe this: enter image description here

into this:

enter image description here

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]: 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 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -