【问题标题】:grouping dataframes in pandas efficiently?有效地将熊猫中的数据框分组?
【发布时间】:2013-08-09 16:55:35
【问题描述】:

我在 pandas 中有以下数据框,其中每一行都有一个唯一索引 (employee),还有一个组标签 type

df = pandas.DataFrame({"employee": ["a", "b", "c", "d"], "type": ["X", "Y", "Y", "Y"], "value": [10,20,30,40]})
df = df.set_index("employee")

我想按type 对员工进行分组,然后计算每种类型的统计数据。我怎样才能做到这一点并获得一个最终的数据帧type x statistic,例如type x (mean of types)?我尝试使用groupby:

g = df.groupby(lambda x: df.ix[x]["type"])
result = g.mean()

这是低效的,因为它为每一行引用df 的索引ix - 有没有更好的方法?

【问题讨论】:

  • 为什么不直接使用g = df.groupby("type")

标签: python numpy pandas dataframe


【解决方案1】:

就像@sza 所说,您可以使用:

In [11]: g = df.groupby("type")

In [12]: g.mean()
Out[12]:
      value
type
X        10
Y        30

更多信息请查看groupby docs...

【讨论】:

    猜你喜欢
    • 2017-10-11
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 2020-12-14
    • 2019-05-03
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多