1

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!

2
  • Can you share the dataframe as python object, so that anyone who wants to work with your data can easily copy and paste. Commented Nov 28, 2022 at 13:20
  • Please provide enough code so others can better understand or reproduce the problem. Commented Nov 28, 2022 at 16:42

1 Answer 1

1

You are looking for the explode Pandas method

df.explode(['col3', 'col4', 'col5']) should do the trick

Sign up to request clarification or add additional context in comments.

1 Comment

It works in a simple and elegant way. Thank you @christospitsi !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.