Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用apply、transform、agg-Python时如何引用groupby索引?_Python_Pandas_Group By_Dataframe_Aggregate - Fatal编程技术网

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

使用apply、transform、agg-Python时如何引用groupby索引?,python,pandas,group-by,dataframe,aggregate,Python,Pandas,Group By,Dataframe,Aggregate,具体来说,假设我们有两个数据帧: df1: df2: 现在我想在df1中按日期分组,取每个组中的值a的和,然后用相应日期中df2中的值B对其进行规范化。像这样的 df1.groupby('date').agg(lambda x: np.sum(x)/df2.loc[x.date,'B']) 问题是聚合、应用和转换都不能引用索引。你知道如何解决这个问题吗?当你调用.groupby('column')时,它使column成为DataFrameGroupBy索引的一部分。并且可以通过.index属性

具体来说,假设我们有两个数据帧:

df1:

df2:

现在我想在df1中按日期分组,取每个组中的值a的和,然后用相应日期中df2中的值B对其进行规范化。像这样的

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

问题是聚合、应用和转换都不能引用索引。你知道如何解决这个问题吗?

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

> df_grouped = df1.groupby('date').sum()
> print df_grouped['A'] / df2['B'].astype(float)
date
12/1/14    0.40
12/2/14     NaN
12/3/14    0.90
12/4/14     NaN
12/5/14     NaN
12/6/14    0.25
dtype: float64
因此,在您的情况下,假设
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']


如果
date
位于
df1.index
中,则将最后一行更改为
df1.groupby(level='date')。应用(f)

这当前处于低质量队列中。请提供一些解释
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