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

Split a Pandas column of lists with different lengths into multiple columns

I have a Pandas DataFrame that looks like:

ID  result
1   [.1,.5]
2   [.4,-.2,-.3,.1,0]
3   [0,.1,.6]

How can split this column of lists into two columns?

Desired result:

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

ID  result_1 result_2 result_3 result_4 result_5
1   .1       .5       NaN      NaN      NaN
2   .4       -.2      -.3      .1       0
3   0        .1       .6       NaN      NaN

I have digged into it a little and found this: Split a Pandas column of lists into multiple columns

but this only seems to apply to list with a constant number of elements.

Thank you so much in advance.

>Solution :

You can do this as suggested in linked post.

import pandas as pd

# your example code
data = {"ID": [1, 2, 3], "result": [[0.1, 0.5], [0.4, -0.2, -0.3, 0.1, 0], [0, 0.1, 0.6]]}
df = pd.DataFrame(data)
print(df)

answer

out = df[['ID']].join(
    pd.DataFrame(df['result'].tolist())
    .rename(columns=lambda x: f'result_{x + 1}')
)

out:

   ID  result_1  result_2  result_3  result_4  result_5
0   1       0.1       0.5       NaN       NaN       NaN
1   2       0.4      -0.2      -0.3       0.1       0.0
2   3       0.0       0.1       0.6       NaN       NaN
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