python - 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 的所有记录,并返回这些记录的工具和数量值。
例如在这种情况下。当 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"])
)
解决方案
在你的情况下,我们可以条件选择然后,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
推荐阅读
- vim - 处理 pymode#run#code_run 时检测到 pymode 错误
- c++ - C++ 中意外的 long long 值
- winforms - 成员函数或访问器如何知道它是否被监视窗口调用?
- python - 触发多个 sql 查询时的异常处理
- windows - powershell中缺少括号错误
- c++ - C/C++ - 查询依赖于平台的换行符(用于内存映射文件)
- javascript - 如何按 itemId 和数量与类型 bundle 和 parentId 与类型 sale_order javascript 进行分组?
- c# - BinaryWriter 给出了错误的大小
- typescript - 从具有所有类型信息的另一个模块中导出类型
- node.js - 如何使用 SendGrid 编写用于发送电子邮件的云函数