Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to move all items of one column to columns in pandas?

I am new to pandas. I am trying to move the items of a column to the columns of dataframe. I am struggling for hours but could not do so.

MWE

import numpy as np
import pandas as pd

df = pd.DataFrame({
    'X': [10,20,30,40,50],
    'Y': [list('abd'), list(), list('ab'),list('abefc'),list('e')]
})

print(df)
    X                Y
0  10        [a, b, d]
1  20               []
2  30           [a, b]
3  40  [a, b, e, f, c]
4  50              [e]

How to get the result like this:

    X  a  b  c  d  e
0  10  1  1  0  1  0
1  20  0  0  0  0  0
2  30  1  1  0  0  0
3  40  1  1  1  0  1
4  50  0  0  0  0  1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can try pandas.Series.str.get_dummies

out = df[['X']].join(df['Y'].apply(','.join).str.get_dummies(sep=','))
print(out)

    X  a  b  c  d  e  f
0  10  1  1  0  1  0  0
1  20  0  0  0  0  0  0
2  30  1  1  0  0  0  0
3  40  1  1  1  0  1  1
4  50  0  0  0  0  1  0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading