pythonpandas

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:

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