Skip to main content
 首页 » 编程设计

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

2024年12月31日24powertoolsteam

我不明白为什么在下面的代码中取消注释 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