首页 > 解决方案 > 根据每个 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

我怎样才能做到这一点?

标签: pythonpandasdataframedata-analysis

解决方案


您可以使用mergefor join on idwith queryfor 过滤:

(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

推荐阅读