python - For循环数据框python
问题描述
我有用df_civic
列调用的数据框 - state ,rank, make/model, model year, thefts
。我想计算每个的AVG和STD。thefts
model year
数据框中的所有年份均采用:years_civic = list(pd.unique(df_civic['Model Year']))
我的循环如下所示:
for civic_year in years_civic:
f = df_civic['Model Year'] == civic_year
civic_avg = df_civic[f]['Thefts'].mean()
civic_std = df_civic[f]['Thefts'].std()
civic_std= np.round(car_std,2)
civic_avg= np.round(car_avg,2)
print(civic_avg, civic_std, np.sum(f))
但是输出不是我需要的,只有正确的输出是来自np.sum(f)
现在输出如下所示:
9.0 20.51 1
9.0 20.51 1
9.0 20.51 1
9.0 20.51 1
9.0 20.51 13
9.0 20.51 15
9.0 20.51 3
9.0 20.51 2
解决方案
Pandas 为聚合数据提供了许多强大的功能。for
通常最好在使用循环之前先考虑这些函数。
例如,您可以使用:
import pandas as pd
import numpy as np
df_civic.groupby("Model Year").agg({"theft": ["mean", np.std]})
更多文档:https ://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.agg.html
关于您的代码,有一些奇怪的东西,car_std
并且car_avg
没有定义。
推荐阅读
- java - 如何处理数字格式异常?
- yaml - 是否可以独立运行 2 个 circleCI 工作流——每次提交一个,每天一个?
- mongoose - Mongoose ObjectID 在参考中保存为字符串
- r - 将置信区间添加到交互的反向转换回归图中
- wicket - 日期选择器 日期文本字段中的日期不会更改
- scala - Scala案例类与对象:它是如何实例化的?
- c# - 如何使用 Microsoft.Graph 验证电子邮件是否为 NDR
- templates - elasticsearch:从现有索引创建索引模板
- powershell - 使用 Powershell 2.0 32 位版本自动安装 Windows FTP 服务器
- akka - 我怎样才能获得演员被终止的信息?