首页 > 解决方案 > DataFrame 游戏:返回与第一个较低或相等日期时间匹配的所有记录

问题描述

谁会喜欢漂亮的 pandas DataFrame 游戏?我有以下难题,但无法解决:

想象一下跟随 pandas DataFrameholdings_df

      datetime    instrument     quantity
0   2021-07-06          $USD  2000.000000
1   2021-07-30          $USD -1841.278610
2   2021-07-30  US3160928731    12.000000
3   2021-07-30  US46137V2410     7.000000
4   2021-07-30  US46137V6056     3.000000
5   2021-07-30  US4642861458     9.000000
6   2021-07-30  US4642865251     9.368500
7   2021-07-30  US4642874329     6.486500
8   2021-07-30  US46434G8556     3.000000
9   2021-07-30  US46434V4234     3.000000
10  2021-07-30  US97717W5215     6.000000
11  2021-08-01          $USD    -1.727408
12  2021-08-02          $USD     1.178727

我需要一个可以执行以下操作的函数:

例如在这种情况下。当 x 为 2021-07-20 时,它应该返回 $USD 2000.000000,当 x 是 2021-07-30 时,它应该返回

        $USD -1841.278610
US3160928731    12.000000
US46137V2410     7.000000
US46137V6056     3.000000
US4642861458     9.000000
US4642865251     9.368500
US4642874329     6.486500
US46434G8556     3.000000
US46434V4234     3.000000
US97717W5215     6.000000

我尝试使用以下函数(其中 x = current_datetime)

holdings_df.set_index("datetime")
holdings_df.iloc[holdings_df.index.get_loc(pd.Timestamp(current_datetime),method="backfill")]

这导致

TypeError: '>' not supported between instances of 'Timestamp' and 'int'

我的日期时间是 int 类型的吗?(已经尝试过holdings_df['datetime'] = pd.to_datetime(holdings_df["datetime"])

标签: pythonpandasdataframedatetime

解决方案


在你的情况下,我们可以条件选择然后,drop_duplicates

n = pd.to_datetime('2021-07-20')
df = df.sort_values('datetime')
df.datetime = pd.to_datetime(df.datetime)
df[df.datetime<=n].drop_duplicates('instrument',keep='last')
Out[10]: 
    datetime instrument  quantity
0 2021-07-06       $USD    2000.0

推荐阅读