I’m trying to convert the following dict: partlistzonesdef (has 50 keys) into a dataframe: Lets say we have the dict:
JavaScript
x
5
1
{1: [60, 127],
2
2: [21, 43, 61, 19],
3
3: [186, 154, 37],
4
4: [99, 68, 80, 87, 128, 98]}
5
How can I convert that to a dataframe like this:
JavaScript
1
11
11
1
Index Area
2
0 1 60
3
1 1 127
4
2 2 21
5
3 2 43
6
4 2 61
7
5 2 19
8
6 3 186
9
7 3 154
10
8 3 37
11
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:
JavaScript
1
2
1
df = pd.Series(d, name='Area').rename_axis('Index').explode().reset_index()
2
Output:
JavaScript
1
18
18
1
>>> df
2
Index Area
3
0 1 60
4
1 1 127
5
2 2 21
6
3 2 43
7
4 2 61
8
5 2 19
9
6 3 186
10
7 3 154
11
8 3 37
12
9 4 99
13
10 4 68
14
11 4 80
15
12 4 87
16
13 4 128
17
14 4 98
18