gpt4 book ai didi

python - 在 MultiIndex 上使用 between_time()?

转载 作者:行者123 更新时间:2023-12-04 14:29:54 25 4
gpt4 key购买 nike

假设我有一个带有 MultiIndex 的 DataFrame,如下所示:

                             col  col  col  col ...
tstp pkt
2016-04-14 04:05:32.321 0 ... ... ... ...
25 ... ... ... ...
2016-04-14 04:05:32.322 1 ... ... ... ...
26 ... ... ... ...
2016-04-14 04:05:32.374 2 ... ... ... ...
...

一旦我确定 begend , 我想用 df[].between_time(beg,end)从 DataFrame 中获取相关行。唯一的问题是, .between_time(beg,end)似乎只适用于 DateTimeIndex:
*** TypeError: Index must be DatetimeIndex

或者是通过 xs() 执行此操作的更合适的方法?
df.xs(slice(beg,end),level='tstp')

最佳答案

有多种方法可以获得您想要的结果:

选项1

可能最好的方法是使用 DataFrame.loc 直接索引到 MutliIndex :

df.loc[beg:end]

选项 2

如果您需要使用 between_time , 你可以 unstack将第二级索引取出,然后使用 between_time最后 stack第二层回:
df.unstack().between_time(beg,end).stack()

选项 3

正如 IanS 提到的, xs会给你一个类似的结果:
df.xs(slice(beg,end),level='tstp')

结论

第一个选项似乎最干净,也是最快的:
>>> timeit df.loc[beg:end]
1000 loops, best of 3: 317 µs per loop

>>> timeit df.unstack().between_time(beg,end).stack()
100 loops, best of 3: 3.35 ms per loop

>>> timeit df.xs(slice(beg,end),level='tstp')
1000 loops, best of 3: 632 µs per loop

Jupyter 笔记本示例 here .

关于python - 在 MultiIndex 上使用 between_time()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36614427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com