Python 无法将我的字典转换为数据帧
我有一本这样的字典Python 无法将我的字典转换为数据帧,python,pandas,dictionary,Python,Pandas,Dictionary,我有一本这样的字典 {'community_0': 30, 'community_1': 29, 'community_2': 15, 'community_3': 16, 'community_4': 123, 'community_5': 9, 'community_6': 36, 'community_7': 71, 'community_8': 95, 'community_9': 21} 我想把它转换成熊猫数据帧。我从dict(dict,orient='index')尝试了pd.Da
{'community_0': 30,
'community_1': 29,
'community_2': 15,
'community_3': 16,
'community_4': 123,
'community_5': 9,
'community_6': 36,
'community_7': 71,
'community_8': 95,
'community_9': 21}
我想把它转换成熊猫数据帧。我从dict(dict,orient='index')尝试了pd.DataFrame
我提到了这篇文章
但这没什么帮助
任何建议都将不胜感激。
pd.DataFrame([d])
会成功。pd.DataFrame([d])
会成功。可以直接从字典中创建一个pd.Series
,然后使用.to\u frame()
将pd.Series
转换为单列数据帧的方法:
import pandas as pd
d = {'community_0': 30,
'community_1': 29,
'community_2': 15,
'community_3': 16,
'community_4': 123,
'community_5': 9,
'community_6': 36,
'community_7': 71,
'community_8': 95,
'community_9': 21}
pd.Series(d).to_frame()
返回:
0
community_0 30
community_1 29
community_2 15
community_3 16
community_4 123
community_5 9
community_6 36
community_7 71
community_8 95
community_9 21
可以直接从字典中创建
pd.Series
,然后使用.to_frame()
方法将pd.Series
转换为单列数据帧:
import pandas as pd
d = {'community_0': 30,
'community_1': 29,
'community_2': 15,
'community_3': 16,
'community_4': 123,
'community_5': 9,
'community_6': 36,
'community_7': 71,
'community_8': 95,
'community_9': 21}
pd.Series(d).to_frame()
返回:
0
community_0 30
community_1 29
community_2 15
community_3 16
community_4 123
community_5 9
community_6 36
community_7 71
community_8 95
community_9 21
这取决于数据帧中需要的结构类型 如果要将dict中的键显示为行值,请使用: ->pd.DataFrame(pd.Series(d)).reset_index() 如果要将dict中的键显示为列,请执行以下步骤:
这取决于数据帧中需要的结构类型 如果要将dict中的键显示为行值,请使用: ->pd.DataFrame(pd.Series(d)).reset_index() 如果要将dict中的键显示为列,请执行以下步骤:
所以
pd.DataFrame(list(d.items()),columns=['Date','DateValue'])
不起作用?我运行了pd.DataFrame(list(d.items())
,其中d
是您提供的字典,它在我这方面起作用。您使用的是什么版本的pandas?您好,欢迎来到Stack Overflow。我建议进行编辑,将字典作为代码包含在内。以后,请不要发布代码的图片,因为它们不可能复制。要了解更多信息,请访问:我可以确认@jezrael的回答对我有效。您应该显示您获得的输出,并包括您尝试生成输出的代码。因此pd.DataFrame(list(d.items()),columns=['Date','DateValue'])
不工作?可能重复我运行的pd.DataFrame(list(d.items())
,其中d
是您提供的字典,它在我这方面起作用。您使用的是什么版本的pandas?您好,欢迎来到Stack Overflow。我建议进行编辑,将字典作为代码包含在内。以后,请不要发布代码的图片,因为它们不可能复制。要了解更多信息,请访问:我可以确认@jezrael的回答对我有效。你应该显示你得到的输出,并包括你试图产生输出的代码。在我的机器上,它创建一个单行数据框,而不是一列。它在您的机器上创建了什么?请注意,OP(原始海报)要求使用单列数据框。是的,我试过了。在我的机器上得到一个包含所有值的原始数据帧,它创建一个单行数据帧,而不是一列。它在您的机器上创建了什么?请注意,OP(原始海报)要求使用单列数据框。是的,我试过了。你得到了一个包含所有值的原始数据帧你的“dict中的键作为列”案例正是benjibat在下面建议的,OP已经说过它对这些数据帧不起作用,而Mine代码将起作用。我已经测试过了。原因是我在一个列表“d=[{”中提到了dictionary,但在给定的问题中,它只是“d={”。这是有区别的。您的“dict中的键作为列”案例正是benjibat在下面建议的,OP已经说过它不适用于Mine代码。我已经对它进行了测试。原因是我在一个列表“d=[{但在给定的问题中,只有“d={”。这会产生不同。