Home > Enterprise >  Expand pandas column list of string values into multiple columns
Expand pandas column list of string values into multiple columns

Time:01-21

I have data in dataframe, the second column is a list of string:

i have data in data frame

The desired outcome would have two separate columns for content.images...:

The desired outcome would be

CodePudding user response:

Assuming this example input:

df = pd.DataFrame({'col1': ['X', 'Y'],
                   'col2': [['ABC', 'DEF'],['GHI', 'JLK', 'MNO']]})

#   col1             col2
# 0    X       [ABC, DEF]
# 1    Y  [GHI, JLK, MNO]

You could apply(pd.Series) and add a custom prefix with add_prefix before doing a join with the original dataframe:

out = (df.drop(columns=['col2'])
         .join(df['col2'].apply(pd.Series).add_prefix('col2_'))
         .fillna('') # optional
      )

output:

  col1 col2_0 col2_1 col2_2
0    X    ABC    DEF       
1    Y    GHI    JLK    MNO

CodePudding user response:

You could try something like:

df[['content.images.0','content.images.1']] = df['content.images'].str.split(', ', expand=True)
  •  Tags:  
  • Related