Pandas 每年向groupby编写一个函数,计算平均值,并以熊猫为单位计算大小

Pandas 每年向groupby编写一个函数,计算平均值,并以熊猫为单位计算大小,pandas,function,pandas-groupby,Pandas,Function,Pandas Groupby,我有一个如下所示的数据帧 Contract_ID Place Contract_Date Price 1 Bangalore 2018-10-25 100 2 Bangalore 2018-08-25 200 3 Bangalore 2019-10-25 300 4 Bangalore

我有一个如下所示的数据帧

Contract_ID    Place         Contract_Date      Price
1              Bangalore     2018-10-25         100
2              Bangalore     2018-08-25         200
3              Bangalore     2019-10-25         300
4              Bangalore     2019-11-25         200
5              Bangalore     2019-10-25         400
6              Chennai       2018-10-25         100
7              Chennai       2018-10-25         200
8              Chennai       2018-10-25         100
9              Chennai       2018-10-25         300
10             Chennai       2019-10-25         400
11             Chennai       2019-10-25         600
从上面我想生成下表使用熊猫

预期产出:

Place       Year     Number_of_Contracts    Average_Price   
Bangalore   2018     2                      150
Bangalore   2019     3                      300
Chennai     2018     4                      175
Chennai     2019     2                      500
尝试下面的代码,它是工作良好。但我想将下面的代码转换为函数。任何帮助都将不胜感激

df['Contract_Date'] = pd.to_datetime(df['Contract_Date'])
df1 = (df.groupby(['Place', df['Contract_Date'].dt.year.rename('Year')])
         .agg(Number_of_Contracts=('Contract_ID','size'),
              Average_Price=('Price','mean'))
         .reset_index())
使用:

然后调用函数:

df1 = func(df)
或使用:

编辑:



此代码段也适用于:

pivot=df.pivot_table(index=['Place',df['Contract_Date'].dt.year.rename('Year')],
               values='Price',aggfunc=['count','sum']).reset_index()
pivot.columns=pivot.columns.droplevel(1)

注意:我的价格栏与你的不同

是否可以在函数中传递列名。所以在以后的文章中,如果我需要和其他列相同的函数,我只需要传递那个函数。@ALI-当然,你能更具体一点吗?哪些列的名称?在本例中为地点、合同日期、合同ID和价格
df1 = df.pipe(func)
def func(df, dates, place, id1, price):
    df[dates] = pd.to_datetime(df[dates])
    return  (df.groupby([place, df[dates].dt.year.rename('Year')])
         .agg(Number_of_Contracts=(id1,'size'),
              Average_Price=(price,'mean'))
         .reset_index())
df1 = func(df, 'Contract_Date', 'Place', 'Contract_ID', 'Price')
print (df1)
       Place  Year  Number_of_Contracts  Average_Price
0  Bangalore  2018                    2            150
1  Bangalore  2019                    3            300
2    Chennai  2018                    4            175
3    Chennai  2019                    2            500
pivot=df.pivot_table(index=['Place',df['Contract_Date'].dt.year.rename('Year')],
               values='Price',aggfunc=['count','sum']).reset_index()
pivot.columns=pivot.columns.droplevel(1)
    Place   Year    count   sum
0   Bangalore   2018    2   200
1   Bangalore   2019    3   300
2   Chennai     2018    4   400
3   Chennai     2019    2   200