我正在使用Python(通常是R家伙)工作,并且正在尝试为特定的应用程序创建此函数。基本上,我试图将“ Month_of_Year”列中每个月的“ CallsPresented”列的平均值作为平均值。我知道我正在使这一过程变得比我需要的复杂。我应该如何做到这一点?
def get_monthly_mean(df):
avg_by_month = []
months = ['Jan', 'Feb', 'Mar', 'Apr', 'June', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
for i in range(11):
x = np.mean(df['CallsPresented'][df.loc[df['Month_of_Year'] == months[i]]])
avg_by_month.append(x)
return months
为什么不只是groupBy
月份列并计算mean
每个组的?
就像是
def get_monthly_mean(df):
df_grouped = df.groupby('Month_of_Year')['CallsPresented'].mean()
#Then you can pass the column to a list or just return the grouped df,
#whatever suits your use case better
return df_grouped
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句