Использование:
def func(df):
df['Contract_Date'] = pd.to_datetime(df['Contract_Date'])
return (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)
Или использовать DataFrame.pipe
:
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