【问题标题】:Pandas to_dict changes index type with outtype='records'Pandas to_dict 使用 outtype='records' 更改索引类型
【发布时间】:2016-08-01 13:59:38
【问题描述】:

我正在尝试在以下 DataFrame 上调用 to_dict 函数:

将熊猫导入为 pd

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

df = pd.DataFrame(数据)

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

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

[{'a': 1, 'b': 90, 'index': 0},
 {'a': 2, 'b': 80, 'index': 1},
 {'a': 3, 'b': 40, 'index': 2},
 {'a': 4, 'b': 60, 'index': 3},
 {'a': 5, 'b': 30, 'index': 4}]

但是,如果我对数据帧执行浮点操作,就会出现我的问题,这会将索引变为浮点数:

(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}]

谁能解释上述行为或推荐解决方法,或验证这是否可能是熊猫错误?如上所示,to_dict 方法中的其他输出类型都不会改变索引。

我已经在 pandas 0.14 和 0.18(最新)上复制了这一点

非常感谢!

【问题讨论】:

  • 这看起来像是一个错误,您应该提交报告here

标签: python pandas indexing records


【解决方案1】:

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

我将在此处传达答案,因此该问题可能会被标记为已解决,并从未回答的 pandas 问题列表中移出。

来自 Github:

与索引无关,只是数据中有任何浮点数据类型

如果您查看code,我们使用 DataFrame.values,它返回一个 NumPy 数组,该数组必须具有单个 dtype(在本例中为 float64)。

--TomAugspurger

该问题的解决方法是:

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

生成 OrderedDict 对象列表

[OrderedDict([('Index', 0), ('a', 1.0), ('b', 90)]),
 OrderedDict([('Index', 1), ('a', 2.0), ('b', 80)]),
 OrderedDict([('Index', 2), ('a', 3.0), ('b', 40)]),
 OrderedDict([('Index', 3), ('a', 4.0), ('b', 60)]),
 OrderedDict([('Index', 4), ('a', 5.0), ('b', 30)])]

【讨论】:

    猜你喜欢
    • 2019-10-15
    • 2016-05-11
    • 2021-09-18
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2016-08-10
    • 2023-03-16
    • 2020-07-24
    相关资源
    最近更新 更多