【问题标题】:Column Order in Pandas Groupby Agg FunctionPandas Groupby Agg 函数中的列顺序
【发布时间】:2014-11-14 21:04:25
【问题描述】:

是否有一种自动方式来维护返回的数据帧的列('C'、'B'、'A')的顺序?

g = df.groupby(['people'])
g['people'].agg({'C' : len,
                 'B' : len,
                 'A' : len,
                })

这会将列返回为 A、B、C 而不是 C、B、A。

我只能找到示例,但找不到 agg 函数本身的文档。

这似乎是一种解决方法:

g = df.groupby(['people'])
g['people'].agg({'C' : len,
                 'B' : len,
                 'A' : len,
                }).reindex_axis(['C','B','A'], axis=1)

【问题讨论】:

  • 你试过使用 OrderedDict 吗?
  • 简短的回答是否定的,但这真的是唯一的方法吗?
  • 我怀疑有没有更简单的方法,问题不在于 pandas - Python(默认)字典并不意味着存储键顺序(这就是创建 OrderedDict 的原因)。

标签: python pandas


【解决方案1】:

OrderedDict 与 pandas-0.18.0-py2.7 的工作令人惊讶:

from collections import OrderedDict
g = df.groupby(['people'])
g['people'].agg( OrderedDict([
                 ('C' , len),
                 ('B' , len),
                 ('A' , len),
                ]) )

【讨论】:

  • 正确。 OrderedDict 让我畏缩不前。好复杂
【解决方案2】:

您可以使用一些索引技巧来按您想要的顺序获取列:

g = df.groupby(['people'])
col_order = ['C', 'B', 'A']
agg_fnxs = [len, len, len]
agg_dict = dict(zip(col_rder, agg_fnxs))
g['people'].agg(agg_dict)[col_corder]

【讨论】:

    猜你喜欢
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 2020-12-05
    • 1970-01-01
    • 2020-12-07
    • 2020-11-08
    相关资源
    最近更新 更多