python - 根据每个 id 的阈值日期在 pandas 中选择行
问题描述
我想从我的 pandas DataFrame 中选择记录在每个 id 的某个日期之前的行。
我对每个 id 都有一些阈值日期:
thresholds = pd.DataFrame({'id':[1, 2, 3], 'threshold_date':pd.date_range('2019-01-01', periods = 3)})
thresholds
id threshold_date
0 1 2019-01-01
1 2 2019-01-02
2 3 2019-01-03
我有一个 DataFrame,其日期在每个 id 的阈值日期之后:
df = pd.DataFrame({'id':[1, 1, 2, 2, 3, 3], 'threshold_date':pd.date_range('2018-12-30', periods = 6), 'value': [0.1, 0.2, 0.3, 0.1, 0.2, 0.3]})
df
id threshold_date value
0 1 2018-12-30 0.1
1 1 2018-12-31 0.2
2 2 2019-01-01 0.3
3 2 2019-01-02 0.1
4 3 2019-01-03 0.2
5 3 2019-01-04 0.3
df = pd.DataFrame({'id':[1, 1, 2], 'threshold_date':pd.date_range('2018-12-30', periods = 3), 'value': [0.1, 0.2, 0.3]})
我想过滤我的 DataFrame,以便我在每个 id 的阈值日期之前只有行:
df_filt = pd.DataFrame({'id':[1, 1, 2], 'threshold_date':pd.date_range('2018-12-30', periods = 3), 'value': [0.1, 0.2, 0.3]})
id threshold_date value
0 1 2018-12-30 0.1
1 1 2018-12-31 0.2
2 2 2019-01-01 0.3
我怎样才能做到这一点?
解决方案
您可以使用merge
for join on id
with query
for 过滤:
(thresholds.merge(df,on='id',how='left',suffixes=('_x',''))
.query("threshold_date_x > threshold_date").reindex(columns=df.columns))
id threshold_date value
0 1 2018-12-30 0.1
1 1 2018-12-31 0.2
2 2 2019-01-01 0.3
推荐阅读
- haproxy - 如何使用 HAproxy 剥离代理协议?
- prolog - Prolog:如何更改组合(N,[H | T],P)的输出以返回对列表,而不仅仅是之前的第一个;?
- ios - In Swift, how to detect if a view controller is "from" a different view controller of a specific class
- ruby-on-rails - Heroku 应用程序错误应用程序不上线
- android - removing intermediary screen with picture
- c - Ingres 将选择提取到 SQLDA
- ios - 使用应用程序组在框架中处理向核心数据的迁移?
- cordova - 离子3中未处理的承诺拒绝警告
- python - 如何获取过去 48 小时的数据 - Django
- python - Pandas:删除所有列中的所有 NaN 值