【问题标题】:Ordered dictionary from pandas dataframe来自熊猫数据框的有序字典
【发布时间】:2018-12-11 21:55:22
【问题描述】:

我有以下代码(Python 2.7):

response2 = requests.get(...)
sample_object = pd.DataFrame(response2.json())['results'].to_dict()

这会从我的 DataFrame 中创建一个 dict,我正在从中创建一个 Json 但是它没有排序:

如何按键排序?意思是isGiftShippingAddress_city 之前等等...

我看到了像this 这样的私人答案,但我无法在我的代码中做到这一点...... 也试过to_dict(into=ordered),但没有任何反应。

有没有一种简单的方法可以从一开始就对其进行排序?或者我必须仅在创建后对其进行排序,如果是,我该怎么做?

【问题讨论】:

    标签: python python-2.7 pandas dictionary


    【解决方案1】:

    您可以将sorted 与自定义键一起使用并输入collections.OrderedDict

    from collections import OrderedDict
    
    sample_object = pd.DataFrame(response2.json())['results'].to_dict()
    sorted_object = OrderedDict(sorted(sample_object.iteritems(), key=lambda x: x[0]))
    

    请注意,Python 3.7 之前的字典被认为是无序的。由于OrderedDictdict 的子类,因此上述方法应该不会导致下游操作出现问题。

    【讨论】:

    • 我使用的是 Python 2.7
    • @jack,那么这个答案会有所帮助,请参阅OrderedDict docs in 2.7 :)。由于您使用的是 2.7,因此您可以根据更新使用dict.iteritems
    猜你喜欢
    • 2021-02-15
    • 2016-11-13
    • 2017-04-20
    • 2015-06-23
    • 2019-03-02
    • 2021-09-03
    • 2019-06-02
    • 2016-10-17
    • 2017-08-02
    相关资源
    最近更新 更多