[英]In pandas, how can I filter for rows where ALL values are higher than a certain threshold? And keep the index columns with the output?
[英]How to replace higher-than-threshold values by the median of previous 3 rows (30 minutes interval) within a group in Pandas?
我有以下 pandas DataFrame:
col1 col2 col3 col4
A 2021-03-28 02:40:00 1.50 0.0
A 2021-03-28 02:40:00 1.80 0.0
A 2021-03-28 02:50:00 0.50 0.0
A 2021-03-28 03:00:00 10.00 0.0
A 2021-03-28 03:10:00 0.00 0.0
A 2021-03-28 03:20:00 0.00 0.0
A 2021-03-28 03:30:00 0.14 0.0
所有大於 5 的col3
值都應替換為過去 30 分鍾的中位數,該中位數對應前 3 行。
預期結果:
col1 col2 col3 col4
A 2021-03-28 02:40:00 1.50 0.0
A 2021-03-28 02:40:00 1.80 0.0
A 2021-03-28 02:50:00 0.50 0.0
A 2021-03-28 03:00:00 1.50 0.0
A 2021-03-28 03:10:00 0.00 0.0
A 2021-03-28 03:20:00 0.00 0.0
A 2021-03-28 03:30:00 0.14 0.0
因此, col3
中的值 10 被1.5
替換,這是前 3 行的中位數: np.median([1.5, 1.8, 0.5])
。
如何為整個 DataFrame 自動化它。
我們可以把它分成兩部分:
col1
的分組內) 第一部分:您可以使用.rolling()
獲得過去 30 分鍾的滾動 window ,然后使用.apply()
將np.median
function 應用於此滾動 Z05B8C74CBD902FBF2DE4ZF14Z 然后.shift()
以便我們獲得上一行的條目。
在這里,我們使用30T
的滾動 window 代替固定數量的間隔作為 window 大小。 這個概念的優點是您的數據不受限於一致且固定的 5 分鍾、10 分鍾或 15 分鍾間隔。 只要您想計算 30 分鍾,Pandas 就會得到正確的工作間隔數。
由於col2
中的時間序列是針對col1
的特定值的 scope(可能是某種分組),我們必須在col1
上進一步使用.groupby()
來相應地處理每個col1
分組的分段時間序列。
第二部分:我們在df['col3'] > threshold
條件下使用.mask()
,如果條件成立,我們用第一部分計算的值替換。
這是代碼:
df['col2'] = pd.to_datetime(df['col2'])
threshold = 5
df['col3'] = (df['col3'].mask(
df['col3'] > threshold,
df.groupby('col1')
.rolling('30T', on='col2')['col3']
.apply(lambda x: np.median(x))
.shift()
.reset_index()['col3'])
)
結果:
print(df)
col1 col2 col3 col4
0 A 2021-03-28 02:40:00 1.50 0.0
1 A 2021-03-28 02:40:00 1.80 0.0
2 A 2021-03-28 02:50:00 0.50 0.0
3 A 2021-03-28 03:00:00 1.50 0.0
4 A 2021-03-28 03:10:00 0.00 0.0
5 A 2021-03-28 03:20:00 0.00 0.0
6 A 2021-03-28 03:30:00 0.14 0.0
df['col3'].rolling(4,min_periods=0).apply(lambda x: np.median(x[-4:-1])if x[-1]>5 else x[-1],raw=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.