![](/img/trans.png)
[英]How can I find rows in Pandas DataFrame where the sum of 2 rows is greater than some value?
[英]How can I find 5 consecutive rows in pandas Dataframe where a value of a certain column is at least 0.5
我有一個帶有 3 列的 Pandas DataFrame; 時間(日期時間對象)、real_generation(浮點)和predicted_generation(浮點)。 我創建了第 4 列“殘差”(也是浮動的),即 real_generation 和 predict_generation 之間的差異。 我現在想檢測連續 5 行的殘差何時至少為 0.5。 數據框看起來像這樣:
Index Time real_generation predicted_generation residual
0 2019-01-01 10:00:00+00:00 0.0 0.239 0.239
1 2019-01-01 11:00:00+00:00 0.126 0.627 0.501
2 2019-01-01 12:00:00+00:00 0.227 0.833 0.606
3 2019-01-01 13:00:00+00:00 0.230 0.833 0.603
4 2019-01-01 14:00:00+00:00 0.245 0.827 0.582
5 2019-01-01 15:00:00+00:00 0.255 0.756 0.501
6 2019-01-01 16:00:00+00:00 0.260 0.627 0.367
7 2019-01-01 17:00:00+00:00 0.255 0.533 0.278
8 2019-01-01 18:00:00+00:00 0.248 0.427 0.179
9 2019-01-01 19:00:00+00:00 0.124 0.233 0.109
我想創建一個函數來查找這些行並打印每個集合的第一個索引。 這意味着打印索引“1”,因為第 1、2、3、4 和 5 行的殘差 > 0.5。 我曾嘗試編寫一個迭代數據幀中所有行的函數,但它非常慢,所以我想知道是否有更快的方法來做到這一點。 我想可能會創建一個額外的布爾列 'residual>0.5',當殘差至少為 0.5 時為 True,當殘差小於 0.5 時為 False,但我真的不知道如何在 Python 中解決這個問題。 有沒有人有任何想法如何實現這一點,或者可能知道一個可能有幫助的功能? 提前致謝!
這是一種pandas
非迭代方法,因此非常有效。
腳步:
True
,否則存儲False
。idx
的numpy.array
。idx
數組用作主數據集的過濾器,減去值 4 以確定運行 5 的第一個索引。示例代碼:
idx = (df['residual'].rolling(window=5).min() >= 0.5).to_numpy()
df.iloc[df.index[idx]-4]
輸出:
Index Time real_generation predicted_generation residual
1 2019-01-01 11:00:00+00:00 0.126 0.627 0.501
執行此操作的一種蠻力方法是首先提取值 >= 0.5 的行:
df_extr = df[df['residual'] >= 0.5]
然后檢查這個提取的索引是否包含一個后續序列,例如
def find_n_seq(ll, n):
row_ids = []
for i, r in enumerate(ll):
window = list(ll[i:i+n])
rg = list(range(r, r+n))
if len(first) < n:
break
if window == rg:
row_ids.append(r)
return row_ids
find_n_seq(list(df_extr.index), 5)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.