Add a new column for each item in a list inside a cell in a Pandas DataFrame

Question:

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

+────────────+───+───+───+───+
| list       |   |   |   |   |
+────────────+───+───+───+───+
| [1,2,3]    | 1 | 2 | 3 |   |
| [1,2]      | 1 | 2 |   |   |
| []         |   |   |   |   |
| [1,2,3,4]  | 1 | 2 | 3 | 4 |
+────────────+───+───+───+───+
Asked By: Led

||

Answers:

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
Answered By: Panda Kim
output = df_test[['A']].join(pd.DataFrame(df_test.unstack().tolist()))

              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
Answered By: God Is One

Yet another way and I think should be faster because it uses values no reshaping or no apply and then concat:

out = pd.concat([df_test, pd.DataFrame(df_test['A'].values.tolist())], axis=1)

print(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
Answered By: SomeDude
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.