Reputation: 11
I have a dataframe with some columns in lists and I would like to flatten these list columns. Below is my dataframe:
df = pd.DataFrame({
'col_1': ['abcd3', 'd4fs3'],
'col_2': ['vfce157', 'dfde28'],
'col_3': [['id_1','id_2'],['id_4','id_6','id_7']],
'col_4': [['p_1','p_2'],['p_3','p_5','p_0']],
'col_5': [['d_1','d_2'],['d_4','d_7','d_8']]
})
df
col_1 | col_2 | col_3 | col_4 | col_5 |
---|---|---|---|---|
abcd3 | vfce157 | [id_1,id_2] | [p_1,p_2] | [d_1,d_2] |
d4fs3 | dfde28 | [id_4,id_6,id_7] | [p_3,p_5,p_0] | [d_4,d_7,d_8] |
The result expected:
col_1 | col_2 | col_3 | col_4 | col_5 |
---|---|---|---|---|
abcd3 | vfce157 | id_1 | p_1 | d_1 |
abcd3 | vfce157 | id_2 | p_2 | d_2 |
d4fs3 | dfde28 | id_4 | p_3 | d_4 |
d4fs3 | dfde28 | id_6 | p_5 | d_7 |
d4fs3 | dfde28 | id_7 | p_0 | d_8 |
Thank you for your help and time!
Upvotes: 1
Views: 284
Reputation: 36
You are looking for the explode Pandas method
df.explode(['col3', 'col4', 'col5'])
should do the trick
Upvotes: 1