Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas unlist one dataframe column in chain

I would like to unlist one Pandas dataframe column into multiple columns in a chain. Like this, but ideally in a chain to help readability as there are more steps afterwards. Here is my example, which doesn’t work.

d1 = {
    'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']],
    'bal':[5,7,8]
}

df2 = pd.DataFrame(d1)

#unlist teams column in chain
res=(df2
   .pd.DataFrame(df2['teams'].to_list(), columns=['team1','team2'])
   .assign(bal2=lambda x: x['bal']*2)
)

#final result like this
d3 = {
    'team1': ['SF','SF','SF'],
    'team2': ['NYG','NYG','NYG'],
    'bal':[5,7,8],
    'bal2':[10,14,16]
}

df4 = pd.DataFrame(d3)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If use DataFrame.pop for extract column and converting to DataFrame then is possible add DataFrame.join for append all another columns:

res= (pd.DataFrame(df2.pop('teams').to_list(), columns=['team1','team2'], index=df2.index)
        .join(df2)
        .assign(bal2 = lambda x: x['bal']*2))

print (res)
  team1 team2  bal  bal2
0    SF   NYG    5    10
1    SF   NYG    7    14
2    SF   NYG    8    16
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading