gpt4 book ai didi

python - 如何在Python中按另一列的条件过滤时取一列的平均值

转载 作者:行者123 更新时间:2023-12-01 09:16:58 25 4
gpt4 key购买 nike

我正在使用 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 月份列并计算每个组的平均值

类似

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

关于python - 如何在Python中按另一列的条件过滤时取一列的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51163175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com