Pandas to_dict用outtype='records'更改索引类型

2024-03-29 06:34:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试对以下数据帧调用to_dict函数:

将熊猫作为pd导入

数据={“a”:[1,2,3,4,5],“b”:[90,80,40,60,30]}

df=pd数据帧(数据)

   a   b
0  1  90
1  2  80
2  3  40
3  4  60
4  5  30

df.reset_index().to_dict("r")

^{pr2}$

但是,如果我对dataframe执行float操作,这会使索引变为float,则会出现问题:

(df*1.0).reset_index().to_dict("r")

[{'a': 1.0, 'b': 90.0, 'index': 0.0},  
{'a': 2.0, 'b': 80.0, 'index': 1.0},  
{'a': 3.0, 'b': 40.0, 'index': 2.0},  
{'a': 4.0, 'b': 60.0, 'index': 3.0},  
{'a': 5.0, 'b': 30.0, 'index': 4.0}]

有人能解释一下以上的行为或者推荐一个解决方法,或者验证这是否是熊猫虫?tou-dict方法中的其他outtype都不会像上面所示那样改变索引。在

我已经在熊猫0.14和0.18(最新版本)上复制了这一点

非常感谢!在


Tags: to数据方法函数版本dataframedfindex
1条回答
网友
1楼 · 发布于 2024-03-29 06:34:29

这个问题已经在github上得到了回答here

我将在这里转达答案,这样问题可能会被标记为已解决,并从未回答的大熊猫问题列表中删除。在

来自Github:

Nothing to do with the index, just the fact that you have any float dtypes in the data

If you look at the code, we use DataFrame.values, which returns a NumPy array, which must have a single dtype (float64 in this case).

TomAugspurger

解决该问题的方法是:

[x._asdict() for x in df.itertuples()]

它生成OrderedDict对象的列表

^{pr2}$

相关问题 更多 >