Monday, July 22, 2019

How to split a list inside a Dataframe cell into rows in Pandas

1
temp = {'name' : ['Edmond', 'ALex'], 'cat' : [['Horror', 'Vengeance', 'Justice'], ['Romance', 'Sacrifice']]}

1
df = pd.DataFrame(temp)

1
df.cat.apply(pd.Series)

1
2
df.cat.apply(pd.Series) \
.merge(df, left_index = True, right_index = True)

1
2
3
df.cat.apply(pd.Series) \
.merge(df, left_index = True, right_index = True) \
.drop(['cat'], axis = 1)

1
2
3
4
5
df.cat.apply(pd.Series) \
.merge(df, left_index = True, right_index = True) \
.drop(['cat'], axis = 1) \
.melt(id_vars = ['name'], value_name = "cat") \
.drop(['variable'], axis= 1)

0 comments:

Post a Comment