python - 使用 apply、transform、agg - Python Pandas 时如何引用 groupby 索引?

标签 python pandas group-by dataframe aggregate

具体来说,假设我们有两个 DataFrame:

df1:

    date    A
0   12/1/14 3
1   12/1/14 1
2   12/3/14 2
3   12/3/14 3
4   12/3/14 4
5   12/6/14 5

df2:

        B
12/1/14 10
12/2/14 20
12/3/14 10
12/4/14 30
12/5/14 10
12/6/14 20

现在想对df1中的date进行groupby,将每组中的值A求和,然后用对应日期df2中的B的值归一化。像这样

df1.groupby('date').agg(lambda x: np.sum(x)/df2.loc[x.date,'B'])

问题是aggregate、apply、transform都不能引用索引。知道如何解决这个问题吗?

最佳答案

当您调用 .groupby('column') 时,它会使 column 成为 DataFrameGroupBy 索引的一部分。它可以通过 .index 属性访问。

因此,在您的情况下,假设 date 不是 df 中索引的一部分,这应该可行:

def f(x):
    return x.sum() / df2.set_index('date').loc[x.index[0], 'B']

df1.set_index('date').groupby(level='date').apply(f)

这会产生:

               A
date            
2014-01-12  0.40
2014-03-12  0.90
2014-06-12  0.25

如果 date 在 df2 的索引中 - 只需在上面的代码中使用 df2.loc[x.index[0], 'B']

如果 datedf1.index 中,将最后一行更改为 df1.groupby(level='date').apply(f).

关于python - 使用 apply、transform、agg - Python Pandas 时如何引用 groupby 索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30221041/

相关文章:

mysql - sql查询某个条件

mysql - 检索每组中的最后一条记录 - MySQL

python - 有人知道如何使用 Ruby 或 Python 在屏幕上显示内容(覆盖任何窗口)吗?

python - Python 3.5 中的 randint 不起作用

python - Travis-CI 找不到 python3-pip 包

python - 选择 Pandas 列中的日期子集

python - 如何使用分配不同颜色的散点图绘制多个分类数据?

python - 将词向量从 Gensim 加载到 SpaCy Vectors 类

Pandas read_excel : only read first few lines

mysql - 从 MySQL 选择行并使用 MAX 和 MIN 进行分组