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

Python Pandas – explode only one column in a dataframe

I have data that looks like this:

["Col1": {0: "str0", 1: "str1", 2: "str2"}, "Col2": {0: ["sub1"], 1: ["sub1", "sub2"], 2: ["sub1", "sub2", "sub3"]}, "Col3": {0: "str0", 1: "str1", 2: "str2"}]

…and I want to get it to look like this as a dataframe by exploding col2:

str0, sub1, str0
str1, sub1, str1
str1, sub2, str1
str2, sub1, str2
str2, sub2, str2
str2, sub3, str2

How do I do this?

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

I have tried both:

df.explode('col2') 

…which doesn’t seem to do anything and:

df1 = pd.concat([pd.DataFrame(){x: np.concatenate(df[x].values}]) for x in 'col2'], axis=1)

…which explodes all the nested values in column 2, but puts them into a separate dataframe.

What am I missing?

>Solution :

You still do explode but assign it back , also notice you used capital in column name

df = df.explode('Col2') 
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