python - 使用 pandas df 分组计算平均值

标签 python pandas dataframe count average

我想获得按日期计算的平均金额,即 例如:-我的数据框就像

应以唯一的月份数作为分母,以金额中所有数据的总和作为分子

Date        amount
2021-12-13  234.89
2021-12-06  456.9
2021-11-26  453.56
2021-11-19  453
2021-11-12  222.4
2021-10-29  123.4
2021-10-22  433.99
2021-10-15  784.99
2021-10-06  678.99

平均值应该是使用 pandas 数据框分组的所有金额值/月数的总和。 在上面的例子中平均值=金额总和/3。

最佳答案

编辑后,IIUC:

df["Month"] = pd.to_datetime(df["Date"]).dt.month
num_of_months = df["Month"].nunique()

df['avg_per_month'] = sum(df['amount'])/num_of_months

关于python - 使用 pandas df 分组计算平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71208616/

相关文章:

python - 无法使用 np 数组中的 dtype 将字符串转换为 float

python - 在Python中同时运行两个函数

python - 从 DataFrame 中提取自定义标题列名称,用 NA 估算缺失的列

python - 使用模糊匹配标准匹配多列数据

python - 我们如何从配置文件(具有列名)的分隔符的基础上拆分列名

python - 根据列列表转置数据框

python - 仅从 pandas 的混合数据类型列中选择整数

python - 为什么 DataFrame.nlargest 不对结果进行排序?

scala - 将数据框列转换为元组列表

python - Pandas:使用 iloc 根据条件更改 df 列值