简体   繁体   中英

Pandas Series of Lists to Dataframe

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM