Python pandas.DataFrame.to_dict行为
我试图将数据帧转换为dict,以便使用这些dict实例化一些类对象。根据文档,我需要的规则是orient='records'。 但是,我注意到,当列名为整数或字符串仅包含整数时,它的行为与我预期的不同:Python pandas.DataFrame.to_dict行为,python,pandas,Python,Pandas,我试图将数据帧转换为dict,以便使用这些dict实例化一些类对象。根据文档,我需要的规则是orient='records'。 但是,我注意到,当列名为整数或字符串仅包含整数时,它的行为与我预期的不同: import pandas as pd df = pd.DataFrame({'a':[1,2,3], 15:[4,5,6], '302':[5,6,7]}) mydict = df.to_dict(orient='records') print(mydict) 返回 [{'_2':4, 'a
import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 15:[4,5,6], '302':[5,6,7]})
mydict = df.to_dict(orient='records')
print(mydict)
返回
[{'_2':4, 'a':1, '_0':5},{'_2':5, 'a':2, '_0':6}, {'_2':6, 'a':3, '_0':7}]
我找到了解决问题的方法,做了:
mydict = list(df.to_dict(orient='index').values())
但我不知道为什么会发生这种情况。我使用的是python3.5
和pandas0.24
。
有什么想法吗?这是一个在pandas 0.24.0中引入并在0.24.1中修复的bug。请参见我看到您的第一个
mydict
返回[{'a':1,15:2,'302':3},{'a':2,15:3,'302':4},{'a':3,15:4,'302':5}]
。您想要什么作为您想要的输出?你能澄清一下吗?@jpp我编辑了我的问题。我不明白为什么我们得不到同样的产出。请注意,我使用的是python 3.5/pandas 0.24抱歉,我重新阅读了您的问题,我使用的是pandas 0.19.2,因此这可能是更高版本的错误。