我有一本字典如下:d = {("Sam","Scotland","23") : 25, ("Oli","England","23") : 28, ("Ethan","Wales","18") : 19}我想将它转换成一个如下所示的 Pandas 数据框:Name Country Age CountSam Scotland 23 25Oli England 23 28Ethan Wales 18 19我试着这样做:df = pd.DataFrame.from_items(d.items(),orient="index", columns=["Name","Country","Age","Count"])但我收到此错误:ValueError: The value in each (key, value) pair must be an array, Series, or dict我很欣赏通过循环遍历元组的每个项目和每个元素是可能的,但是有没有更干净的方法来做到这一点?
2 回答
Qyouu
TA贡献1786条经验 获得超11个赞
您可以直接使用pd.DataFrame.from_dict字典。这将根据您的输入字典键创建一个键。您可以将其转换为,然后使用:tupleMultiIndexreset_index
cols = ['Name', 'Country', 'Age', 'Count']
df = pd.DataFrame.from_dict(d, orient='index', columns=cols[-1])
df.index = pd.MultiIndex.from_tuples(df.index, names=cols[:-1])
df = df.reset_index()
添加回答
举报
0/150
提交
取消