3

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'

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

I'd suggest you start with your DataFrame like you have already got:

slide   level    level_title
1       2         Pepsi
3       1         Pepper

Add a couple of columns with nothing in them:

In [24]: df['level1'] = pd.np.nan

In [25]: df['level2'] = pd.np.nan

Then set the values as needed with some conditional wizardry:

In [40]: df.loc[df['level'] == 2, 'level1'] = df.level_title

In [41]: df.loc[df['level'] == 1, 'level2'] = df.level_title

In [42]: df
Out[42]: 
   slide  level level_title level1  level2
0      1      2       Pepsi  Pepsi     NaN
1      3      1      Pepper    NaN  Pepper

(Spot the 'deliberate' mistake that I put the levels and the titles the wrong way round. But you get the idea!)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.