[英]A function in pandas or numpy to filter column by list of values that follows it
給定一個數據框df:
import pandas as pd
df = pd.DataFrame({"changes":['increase', 'constant', 'constant', 'constant', 'decline', 'constant', 'constant', 'increase', 'constant', 'constant', 'constant','decline', 'constant', 'constant', 'constant',})
輸出:
變化 |
---|
增加 |
持續的 |
持續的 |
持續的 |
衰退 |
持續的 |
持續的 |
增加 |
持續的 |
持續的 |
持續的 |
衰退 |
持續的 |
持續的 |
持續的 |
任務是刪除decline
的行和后面的constant
。 我不想刪除increase
和它之后的constant
。
這種情況下的預期輸出應如下所示:
變化 |
---|
增加 |
持續的 |
持續的 |
持續的 |
增加 |
持續的 |
持續的 |
持續的 |
df = pd.DataFrame({"changes":['increase', 'constant', 'constant', 'constant', 'decline', 'constant', 'constant', 'increase', 'constant', 'constant', 'constant','decline', 'constant', 'constant', 'constant']})
### Build group
df['group'] = df['changes'].ne(df['changes'].shift()).cumsum()
df
###
changes group
0 increase 1
1 constant 2
2 constant 2
3 constant 2
4 decline 3
5 constant 4
6 constant 4
7 increase 5
8 constant 6
9 constant 6
10 constant 6
11 decline 7
12 constant 8
13 constant 8
14 constant 8
創建掩碼以過濾掉不需要的數據
mask_1 = df['changes'].eq('decline') & df['changes'].shift(-1).eq('constant')
mask_2 = df['changes'].eq('constant') & df['changes'].shift().eq('decline')
groups = df.loc[mask_1 | mask_2, 'group']
groups
表示group
3
, 4
, 7
, 8
應排除
將過濾后的數據分配給result
result = df[~df['group'].isin(groups)].drop(columns=['group'])
result
###
changes
0 increase
1 constant
2 constant
3 constant
4 increase
5 constant
6 constant
7 constant
您可以使用 shift() 但這不會給出正確的結果 IMO。 為了獲得一致且強大的輸出,您可以執行以下操作:
decline_idx = df.query("changes == 'decline'").index
constant_idx = df.loc[decline_idx+1].query("changes == 'constant'").index
df = df.drop(decline_idx.union(constant_idx)) if not constant_idx.empty else df
或者如果你想放棄decline
,你可以直接放棄而不檢查constant
:
df.drop(decline_idx.union(constant_idx), inplace=True)
打印(df):
changes
0 increase
1 constant
2 constant
3 constant
6 constant
7 increase
8 constant
9 constant
10 constant
13 constant
14 constant
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.