python-3.x - 通过根据特定条件比较所有行来查找数据框中的匹配行
问题描述
我对python相当陌生,如果有人能引导我朝着正确的方向前进,我将不胜感激。
我有一个数据集,每行都有独特的交易。我需要找到在某些条件下匹配的所有行。基本上,找到任何符合特定条件的抵消交易。例如:
查找 REF_RATE 相同的交易,RECEIVE 相差 5 天,MATURITY_DATE 相差 7 天。我附上了数据的图像。
谢谢你。
解决方案
您可以使用groupby
来实现这一点。根据您对此问题的具体要求,Find trades that have the same REF_RATE, RECEIVE is within a difference of 5, MATURITY_DATE is with 7 days of each other
您可以这样进行。
#sample data created from the image of your dataset
>>> data = {'Maturity_Date':['2/01/2021','10/01/2021','10/01/2021','6/06/2021'],'Trade_id':['10484','12880','11798','19561'],'REF_RATE':['BBSW','BBSW','OIS','BBSW'],'Recive':[1.5,1.25,2,10]}
>>> df = pd.DataFrame(data)
>>> df
Maturity_Date Trade_id REF_RATE Recive
0 2/01/2021 10484 BBSW 1.50
1 10/01/2021 12880 BBSW 1.25
2 10/01/2021 11798 OIS 2.00
3 6/06/2021 19561 BBSW 10.00
#convert Maturity_Date to datetime format and sort REF_RATE by date if needed
>>> df['Maturity_Date'] = pd.to_datetime(df['Maturity_Date'], dayfirst=True)
>>> df['Maturity_Date'] = df.groupby('REF_RATE')['Maturity_Date'].apply(lambda x: x.sort_values()) #if needed
>>> df
Maturity_Date Trade_id REF_RATE Recive
0 2021-01-02 10484 BBSW 1.50
1 2021-01-10 12880 BBSW 1.25
2 2021-01-10 11798 OIS 2.00
3 2021-06-06 19561 BBSW 10.00
#groupby of REF_RATE and apply condition on date and receive column
>>> df['date_diff>7'] = df.groupby('REF_RATE')['Maturity_Date'].diff() / np.timedelta64(1, 'D') > 7
>>> df['rate_diff>5'] = df.groupby('REF_RATE')['Recive'].diff() > 5
>>> df
Maturity_Date Trade_id REF_RATE Recive date_diff>7 rate_diff>5
0 2021-01-02 10484 BBSW 1.50 False False
1 2021-01-10 12880 BBSW 1.25 True False #date_diff true as for BBSW Maturity date is more than 7
2 2021-01-10 11798 OIS 2.00 False False
3 2021-06-06 19561 BBSW 10.00 True True #rate_diff and date_diff true because date>7 and receive difference>5
推荐阅读
- python-3.x - 使用 Revit API 更改元素的族和类型
- android - 将高阶函数作为属性传递的测试方法
- python - 如何在 wxPython 中获取具有不同 DPI 和分辨率的小部件/字体大小?
- angular - 如何在angular8中添加对扩展服务的依赖
- php - 使用正则表达式从 HTML 中提取标签属性
- java - cucumber.runtime.CucumberException:调用 stepDefinition 失败
- ios - 如何将带有委托的数据从页脚单元格传递到视图控制器?
- angularjs - Angularjs:如何乘以从 angularjs 中的总过滤器获得的总和以显示不同货币价值的总和?
- javascript - 使用 Jest 在自定义 Ajax 函数中模拟响应值
- mysql - 从 Heroku 上的 Node.js 连接到 CloudSQL