Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading