Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas dataframe issue

I have this dictionary:

d = {1 : [ '2' , 'Pepsi' ], 3 : [ '1' , 'Pepper' ]}

df = pd.DataFrame([[slide, i[0], i[1]] for slide, item in d.items() for i in
item], columns=['Slide', 'Level', 'Level Title'])

I want to have the following output:

slide   level    'level1 title'   'level2 title'
1       2                          Pepsi
3       1         Pepper

So far, my code outputs this:

slide   level    'level title'
1       2         Pepsi
3       1         Pepper

Basically when the first item in the list is 1, the second item in the list should go to 'level1 title', and when the item is 2, the second item should go to 'level2 title'

like image 263
S.Al Avatar asked Mar 01 '26 10:03

S.Al


1 Answers

If there are only two levels, then you can use list comprehension , like this -

In [12]: df = pd.DataFrame([[slide, item[0], item[1], ''] if item[0] == '1' else [slide, item[0], '', item[1]] 
for slide, item in d.items()], columns=['Slide', 'Level', 'Level1 Title', 'Level2 Title'])

In [13]: df
Out[13]:
   Slide Level Level1 Title Level2 Title
0      1     2                     Pepsi
1      3     1       Pepper
like image 141
Anand S Kumar Avatar answered Mar 04 '26 01:03

Anand S Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!