Home > other >  Python Pandas - explode only one column in a dataframe
Python Pandas - explode only one column in a dataframe

Time:07-05

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?

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?

CodePudding user response:

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

df = df.explode('Col2') 

CodePudding user response:

Another way

col2_df = pd.DataFrame(df["Col2"].tolist())
  • Related