[英]Create a pandas dataframe from a dictionary of dictionaries
I have a dictionary of dictionaries similar to the following:我有一个类似于以下的字典:
data_dict = {
'first_entry': {'a': 345, 'b': 8484},
'second_entry': {'a': 3423, 'b': 848}
}
I would like to create a dataframe of all these values, as follows:我想创建所有这些值的 dataframe ,如下所示:
pd.DataFrame(
[list(data_dict[key].values()) for key in data_dict.keys()],
columns = list(data_dict[list(data_dict.keys())[0]].keys()))
I'm a bit concerned about the approach taken here with respect to accessing the keys and such.我有点担心这里在访问密钥等方面采取的方法。
Note - in the above the values first_entry
and second_entry
are not reliable, but the values of a
and b
are reliable.注意 - 在上面的值
first_entry
和second_entry
不可靠,但a
和b
的值是可靠的。 In the actual data I have ~500 or so nested dictionaries, (so first_entry
... five_hundredth_entry
using the above syntax).在实际数据中,我有大约 500 个嵌套字典(所以
first_entry
... five_hundredth_entry
使用上述语法)。
You only need DataFrame.from_dict
with orient='index'
.你只需要
DataFrame.from_dict
和orient='index'
。 We can reset the index at the end optionally.我们可以选择在最后重置索引。
new_df = pd.DataFrame.from_dict(data_dict, orient='index').reset_index(drop=True)
print(new_df)
Output Output
a b
0 345 8484
1 3423 848
IIUC国际大学联盟
pd.DataFrame(d).T.reset_index(drop=True)
a b
0 345 8484
1 3423 848
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.