Splitting series with single column that contains list, into multiple columns with single values

Viewed 126

Given a Series object which I have pulled from a dataframe, for example through:

columns = list(df)
for col in columns:
    s = df[col] # The series object

The Series contains a <class 'list'> in each row, making it look like this:

0       [116, 66]
2       [116, 66]
4       [116, 66]
6       [116, 66]
8       [116, 66]
          ...
1498    [117, 66]
1500    [117, 66]
1502    [117, 66]
1504    [117, 66]
1506    [117, 66]

How could I split this up, so it becomes two columns in the Series instead?

0       116   66
2       116   66
          ...
1506    116   66

And then append it back to the original df?

1 Answers

From Ch3steR's comment of using pd.DataFrame(s.tolist()), I managed to get the answer I was looking for, including renaming the columns in the new dataframe to also include the column name of the existing Series.

columns = list(df)
for col in columns:
    df2 = pd.DataFrame(df[col].tolist())
    df2.columns = [col+"_"+str(y) for y in range(len(df2.columns))]
    print(df2)

To keep this shorter, as also suggested by Ch3steR, we can simplify the above to:

columns = list(df)
for col in columns:
    df2 = pd.DataFrame(df[col].tolist()).add_prefix(col)
    print(df2)

Which in my case, gives the following output:

     FrameLen_0  FrameLen_1 
0           116          66
1           116          66
2           116          66
3           116          66
4           116          66
..          ...         ...
749         117          66
750         117          66
751         117          66
752         117          66
753         117          66
Related