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

Add a new column for each item in a list inside a row Pandas

Assuming I have this table

import pandas as pd

df_test = pd.DataFrame()
df_test = df_test.assign(A=[[1,2,3], [1,2], [], [1,2,3,4]])
df_test


+────────────+
| list       |
+────────────+
| [1,2,3]    |
| [1,2]      |
| []         |
| [1,2,3,4]  |
+────────────+

What I want to do is to add a column for every item in a list inside a row.

The output I would like to have looks like this

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

+────────────+───+───+───+───+
| list       |   |   |   |   |
+────────────+───+───+───+───+
| [1,2,3]    | 1 | 2 | 3 |   |
| [1,2]      | 1 | 2 |   |   |
| []         |   |   |   |   |
| [1,2,3,4]  | 1 | 2 | 3 | 4 |
+────────────+───+───+───+───+

>Solution :

out = df_test[['A']].join(df_test['A'].apply(pd.Series))

out

     A              0       1       2       3
0   [1, 2, 3]       1.0     2.0     3.0     NaN
1   [1, 2]          1.0     2.0     NaN     NaN
2   []              NaN     NaN     NaN     NaN
3   [1, 2, 3, 4]    1.0     2.0     3.0     4.0
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