Skip to content
Advertisement

Convert dictionary into dataframe (with repeated keys as rows)

I’m trying to convert the following dict: partlistzonesdef (has 50 keys) into a dataframe: Lets say we have the dict:

{1: [60, 127],
 2: [21, 43, 61, 19],
 3: [186, 154, 37],
 4: [99, 68, 80, 87, 128, 98]}

How can I convert that to a dataframe like this:

    Index Area
0   1     60
1   1     127
2   2     21
3   2     43
4   2     61
5   2     19
6   3     186
7   3     154
8   3     37

And so on?

Advertisement

Answer

Create a Series and transform each element of the list to a row with explode then reset_index to get expected outcome:

df = pd.Series(d, name='Area').rename_axis('Index').explode().reset_index()

Output:

>>> df
    Index Area
0       1   60
1       1  127
2       2   21
3       2   43
4       2   61
5       2   19
6       3  186
7       3  154
8       3   37
9       4   99
10      4   68
11      4   80
12      4   87
13      4  128
14      4   98
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement