Home > Enterprise >  Pandas Series of Lists to Dataframe
Pandas Series of Lists to Dataframe

Time:12-10

Given a pandas series of lists, where every list contains the same number of lists and each 'sublist' has the same length of values, like the following example:

import pandas as pd

s = pd.Series([
                [[1, 2], [3, 4], [5, 6]], 
                [[7, 8], [9, 10], [11, 12]],
                [[13, 14], [15, 16], [17, 18]],
                ], index=[10,20,30])
s
10          [[1, 2], [3, 4], [5, 6]]
20       [[7, 8], [9, 10], [11, 12]]
30    [[13, 14], [15, 16], [17, 18]]
dtype: object

Is it possible the series to be converted to a pandas DataFrame with the following structure:

    col1  col2  col3
10     1     3     5
10     2     4     6
20     7     9    11
20     8    10    12
30    13    15    17
30    14    16    18

CodePudding user response:

if pandas version > 1.3.0:

cols = ['col1', 'col2', 'col3']
pd.DataFrame(s.tolist(), index=s.index, columns=cols).explode(cols)

result:

    col1  col2  col3
10     1     3     5
10     2     4     6
20     7     9    11
20     8    10    12
30    13    15    17
30    14    16    18
  • Related