0

I have a nested dictionary like this:

{('1', 'Jim'): 'Pass',
 ('2', 'Nik'): 'Fail',
 ('3', 'Anna'): 'Pass',
 ('4', 'Bob'): 'Fail',
 ('5', 'Sam'): 'Pass',
 ('6', 'Rob'): 'Fail'}

I want to convert this to a data frame like this:

DataFrame('ID':[1,2,3,4,5,6], 
'Name':[Jim, Nik, Anna, Bob, Sam, Rob], 
Result: [Pass, Fail, Pass, Fail, Pass, Fail])

Kindly help!

2 Answers 2

1

Create a series from it, reset its index, and rename the columns:

df = pd.Series(your_dict).reset_index().set_axis(['ID', 'Name', 'Result'], axis=1)

Output:

>>> df
  ID  Name Result
0  1   Jim   Pass
1  2   Nik   Fail
2  3  Anna   Pass
3  4   Bob   Fail
4  5   Sam   Pass
5  6   Rob   Fail
Sign up to request clarification or add additional context in comments.

Comments

0
import pandas as pd

dct = {('1', 'Jim'): 'Pass',
       ('2', 'Nik'): 'Fail',
       ('3', 'Anna'): 'Pass',
       ('4', 'Bob'): 'Fail',
       ('5', 'Sam'): 'Pass',
       ('6', 'Rob'): 'Fail'}

# Split keys and values of the dict into separate columns; 
# the result has 2 columns:
df = pd.DataFrame(dct.items(), columns=['ID_Name', 'Result'])

# Split the column of tuples into 2 new columns:
df[['ID', 'Name']] = pd.DataFrame(df['ID_Name'].tolist(), index=df.index)

# Remove the intermediate column of tuples (no longer needed), 
# rearrange columns:
df = df[['ID', 'Name', 'Result']]
print(df)
#   ID  Name Result
# 0  1   Jim   Pass
# 1  2   Nik   Fail
# 2  3  Anna   Pass
# 3  4   Bob   Fail
# 4  5   Sam   Pass
# 5  6   Rob   Fail

Comments

Your Answer

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