考虑一个具有4列的数据框-
所以我要寻找与货币对,名义数量相似但交易类型相反的行-买和卖
import pandas as pd
trade_id=[1,2,3,4,5,6] #dtype = int64
ccy_pairs=['AUD','AUD','GBP','EUR','NZD','NZD']#dtype = str
notional=[1,1,1.5,2,6,7]#dtype = int64
trade_type=['buy','sell','buy','sell','buy','buy']#dtype = str
value_date=['01012018', '03012019', '05062018','03062018','07082018','09082020']#dtype = datetime
df=pd.DataFrame() #dataframe comprising of many other columns
df['trade_id']=trade_id
df['ccy_pairs']=ccy_pairs
df['notional']=notional
df['trade_type']=trade_type
df['value_date']=value_date
#Output expected - Looking to highlight the offsetting legs of the trade ( i.e. trades having same notional and ccy pair,
#but different trade types )
Trade Id|CCY Pair|Notional|Trade_type|value_date
1 aud 1 Buy 01012018
3 gbp 1.5 Buy 05062018
4 eur 2 Sell 07062018
5 nzd 6 Buy 07082018
6 nzd 7 Buy 09092020
这意味着,在CCY an Notional上匹配但有相反的腿(买入和卖出)的2行导致其中一个(两个)掉线了
答案 0 :(得分:1)
您需要:
didReceiveApplicationContext
输出
df.drop_duplicates(subset=['ccy_pairs','notional'], keep='first', inplace=True)
有关更多详细信息,请参见this
答案 1 :(得分:1)
要删除的两行的条件(其中之一):
“(ccy_pairs
和notional
中有重复的行,并且(trade_type
中没有重复)”
drop_duplicates
不会检查对立的腿(买卖)。
您可以尝试以下操作(我假设总是删除第二个查找内容(.index[1]
):
dups = df.ccy_pairs[df.ccy_pairs.duplicated()] # to get AUD and NZD
for i in dups: # to check opposing legs
if df.trade_type[df.ccy_pairs == i].nunique() == 2:
df.drop(df[df.ccy_pairs == i].index[1], inplace=True)