gpt4 book ai didi

python - 在 sort_index 之后使用 pandas 字符串选择

转载 作者:太空宇宙 更新时间:2023-11-04 04:41:11 24 4
gpt4 key购买 nike

我不明白为什么在下面的代码中取消注释 ts = ts.sort_index() 会抛出 ErrorKey:

import datetime
import pandas as pd

df = pd.DataFrame({
'x': [2, 1, 3],
'd': [
datetime.datetime(2018, 5, 21),
datetime.datetime(2018, 5, 20),
datetime.datetime(2018, 5, 22)
]
})

ts = df.set_index('d')
#ts = ts.sort_index()

ts['2018-05-21']

我的假设是 sort_index 以某种方式生成了一个新索引,因此破坏了字符串选择,但我找不到任何证据。

为了提供一些上下文,我想对这个时间序列进行排序以选择一个时间范围(例如,ts['2018-05-21':])。如果我不对其进行排序,它适用于上面的示例,但不适用于时间范围。

最佳答案

我会推荐使用.loc

#ts = df.set_index('d')
#ts = ts.sort_index()
ts.loc['2018-05-21':,:]
Out[102]:
x
d
2018-05-21 2
2018-05-22 3

关于python - 在 sort_index 之后使用 pandas 字符串选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50572686/

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