如何在使用apply,transform,agg-Python Pandas时引用groupby索引? [英] How to reference groupby index when using apply, transform, agg - Python Pandas?
问题描述
具体来说,假设我们有两个DataFrames:
$ b $ df1:
日期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中对groupby日期进行计算,并将每个组中的值A加起来,然后用相应的df2中的B值对其进行归一化日期。像这样
df1.groupby('date')。agg(lambda x:np.sum(x)/ df2。 loc [x.date,'B'])
问题是聚合,应用,变换可以参考索引。任何想法如何解决这个问题?
当您调用 .groupby('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
日期
2014-01-12 0.40
2014-03-12 0.90
2014-06-12 0.25
如果 date
位于df2的索引中 - 只需使用 df2.loc [x.index [0],'B']
in上面的代码。
如果 date
位于 df1.index
将最后一行更改为 df1.groupby(level ='date')。apply(f)
。
To be concrete, say we have two DataFrames:
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
Now I want to groupby date in df1, and take a sum of value A in each group and then normalize it by the value of B in df2 in the corresponding date. Something like this
df1.groupby('date').agg(lambda x: np.sum(x)/df2.loc[x.date,'B'])
The question is that neither aggregate, apply, nor transform can reference to the index. Any idea how to work around this?
When you call .groupby('column')
it makes column
to be part of DataFrameGroupBy
index. And it is accessible through .index
property.
So, in your case, assuming that date
is NOT part of index in either df
this should work:
def f(x):
return x.sum() / df2.set_index('date').loc[x.index[0], 'B']
df1.set_index('date').groupby(level='date').apply(f)
This produces:
A
date
2014-01-12 0.40
2014-03-12 0.90
2014-06-12 0.25
If date
is in index of df2 - just use df2.loc[x.index[0], 'B']
in the above code.
If date
is in df1.index
change the last line to df1.groupby(level='date').apply(f)
.
这篇关于如何在使用apply,transform,agg-Python Pandas时引用groupby索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!