【问题标题】:Pandas Columns to Dict Preserving OrderPandas Columns to Dict Preserving Order
【发布时间】:2017-01-22 12:35:00
【问题描述】:

给定以下数据框:

df = pd.DataFrame({'a':['a','c','b'],
                   'b':['foo','bar','baz']})
df
    a   b
0   a   foo
1   c   bar
2   b   baz

当我从列中创建一个字典时,我得到了这个:

dict(zip(df.a,df.b))
{'a': 'foo', 'b': 'baz', 'c': 'bar'}

您会注意到它会自动对键列 (a) 进行排序。

我的问题是:如何避免这种情况?

我想要一个看起来像这样的字典:

{'a': 'foo', 'c': 'bar', 'b': 'baz', }

提前致谢!

【问题讨论】:

  • 但关键字典顺序不一定是插入顺序这与熊猫无关,如果要保留插入顺序,则必须使用orderedDict
  • 您无法控制字典中键的顺序。
  • OrderedDict 有效!谢谢,EdChum。如果您想将其发布为答案,我会相应地标记。

标签: python-3.x sorting pandas dictionary


【解决方案1】:

无法控制 Python 字典中键的顺序。标准库为此包含一个不同的数据结构 - OrderedDict - 它会记住添加键的顺序。

在这种情况下,您可以通过

In [39]: OrderedDict(df.to_records(index=False))
Out[39]: OrderedDict([('a', 'foo'), ('c', 'bar'), ('b', 'baz')])

【讨论】:

    猜你喜欢
    • 2022-08-25
    • 2017-01-07
    • 2021-10-06
    • 1970-01-01
    • 2022-12-01
    • 2022-12-26
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多