[英]Filter values in pandas dataframe based on complex columns conditions
我有一個看起來像這樣的 dataframe
dict = {'trade_date': {1350: 20151201,
6175: 20151201,
3100: 20151201,
5650: 20151201,
3575: 20151201,
1: 20170301,
2: 20170301},
'comId': {1350: '257762',
6175: '1038328',
3100: '315476',
5650: '658776',
3575: '329376',
1: '123456',
2: '987654'},
'return': {1350: -0.0018,
6175: 0.0023,
3100: -0.0413,
5650: 0.1266,
3575: 0.0221,
1: '0.9',
2: '0.01'}}
df = pd.DataFrame(dict)
the expected output should be like this:
dict2 = {'trade_date': {5650: 20151201,
1: 20170301},
'comId': {5650: '658776',
1: '123456'},
'return': {5650: 0.1266,
1: '0.9'}}
我需要根據以下條件對其進行過濾:對於每個trade_date
值,我只想根據return
列中的值保留前 20% 的條目。 因此,對於此示例,它將過濾掉comId
值為658776
且return
值為0.1266
的公司之外的所有內容。
請記住,可能有與更多公司相關的trade_dates
。 在這種情況下,它應該向上或向下舍入到最接近的 integer。 例如,如果有 9 家公司與某個日期相關聯,則 20% * 9 = 1.8,因此它應該僅根據列return
中的值保留前兩個。
任何想法如何最好地解決這個問題,我有點迷茫?
我認為這應該有效:
df\
.groupby("trade_date")\
.apply(lambda x: x[x["return"] >
x["return"].quantile(0.8, interpolation="nearest")])\
.reset_index(drop=True)
您可以使用groupby().transform
來獲取每行的閾值。 這會比groupby().apply
快一點:
thresholds = df.groupby('trade_date')['return'].transform('quantile',q=.8)
df[df['return'] > thresholds]
Output:
trade_date comId return
5650 20151201 658776 0.1266
創建一個臨時變量,僅存儲具有相同 trade_date 的行。 然后使用這個: df.sort_values(by='return', ascending=False) 然后刪除底部的 80%。 循環遍歷所有可能的日期,每次獲得 20%,append 到新的 dataframe。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.