pandas 将字典转换为熊猫中的数据框列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33740370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
converting dictionary to dataframe column in pandas
提问by Prashant Sharma
I have a nested dictionary like this
我有一个这样的嵌套字典
d = {1 : {'we': 26, 'is': 112},
2 : {'tp': 26, 'fp': 91},
3 : {'pp': 23, 'kj': 74}}
I want to change it to a dataframe column such that outer dict keys become rows and its element act as an element of the column.
我想将其更改为数据框列,以便外部 dict 键变为行,其元素充当列的元素。
Desired Output:
期望输出:
rows col1
1 'we': 26, 'is': 112
2 'tp': 26, 'fp': 91
3 'pp': 23, 'kj': 74
回答by mattvivier
If that's what you have in your dictionary, it isn't necessarily going to preserve the order of the keys for the inner dict.
如果这就是您的字典中的内容,则不一定要保留内部字典的键顺序。
import pandas as pd
d = {1 : {'we': 26, 'is': 112},
2 : {'tp': 26, 'fp': 91},
3 : {'pp': 23, 'kj': 74}}
# Replace the inner dicts with their string representations
for i in d:
d[i] = str(d[i])
# Convert to dataframe
df = pd.DataFrame.from_dict(d, orient='index').reset_index()
# Clean up column names
df.rename(columns={'index': 'row', 0: 'col1'}, inplace=True)