将嵌套字典转换为具有键和值的数据框是列
convert nested dictionary to dataframe with keys & values are columns
我有一个这样的嵌套字典:
{('1', 'Jim'): 'Pass',
('2', 'Nik'): 'Fail',
('3', 'Anna'): 'Pass',
('4', 'Bob'): 'Fail',
('5', 'Sam'): 'Pass',
('6', 'Rob'): 'Fail'}
我想将其转换为这样的数据框:
DataFrame('ID':[1,2,3,4,5,6],
'Name':[Jim, Nik, Anna, Bob, Sam, Rob],
Result: [Pass, Fail, Pass, Fail, Pass, Fail])
请帮忙!
从中创建一个系列,重置其索引,并重命名列:
df = pd.Series(your_dict).reset_index().set_axis(['ID', 'Name', 'Result'], axis=1)
输出:
>>> 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
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
我有一个这样的嵌套字典:
{('1', 'Jim'): 'Pass',
('2', 'Nik'): 'Fail',
('3', 'Anna'): 'Pass',
('4', 'Bob'): 'Fail',
('5', 'Sam'): 'Pass',
('6', 'Rob'): 'Fail'}
我想将其转换为这样的数据框:
DataFrame('ID':[1,2,3,4,5,6],
'Name':[Jim, Nik, Anna, Bob, Sam, Rob],
Result: [Pass, Fail, Pass, Fail, Pass, Fail])
请帮忙!
从中创建一个系列,重置其索引,并重命名列:
df = pd.Series(your_dict).reset_index().set_axis(['ID', 'Name', 'Result'], axis=1)
输出:
>>> 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
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