首页 > 解决方案 > 在 Pandas DataFrame 中满足条件时范围内的平均数据点

问题描述

我有一个非常大的数据集,有超过 400,000 行并且还在增长。我了解您不应该使用 itrows 来修改熊猫数据框。但是,我对在这种情况下应该做什么有点迷茫,因为我不确定我是否可以使用 .loc() 或一些滚动过滤器以我需要的方式修改数据框。我试图弄清楚是否可以在满足条件时获取数据框并平均范围。例如:

健康)状况 温度。 压力
1 8 20
1 7 23
1 8 22
1 9 21
0 4 33
0 3 35
1 9 21
1 11 20
1 10 22

当条件为 == 1 时,输出的数据帧将如下所示:

健康)状况 平均 温度。 平均 压力
1 8 21.5
1 10 21

有没有人尝试过类似的事情可以让我走上正确的道路?我正在考虑使用这样的东西:

df = pd.csv_read(csv_file)

for index, row in df.iterrows():
   if row['condition'] == 1:
      #start index = first value that equals 1
   else: #end index & calculate rolling average of range
      len = end - start
      new_df = df.rolling(len).mean()

我知道我的代码不是很好,我也知道我可以强制它执行与上面所示类似的操作,但正如我所说,它有很多行并且还在继续增长,所以我需要提高效率。

标签: python-3.xpandasdataframe

解决方案


尝试:

result = df.groupby((df.Condition != df.Condition.shift()).cumsum()).apply(
    lambda x: x.rolling(len(x)).mean().dropna()).reset_index(drop=True)
print(result.loc[result.Condition.eq(1)]) # filter by required condition

输出:

   Condition  Temp.  Pressure
0        1.0    8.0      21.5
2        1.0   10.0      21.0

推荐阅读