使用.loc()方法时出现Pandas KeyError错误。

6 浏览
0 Comments

使用.loc()方法时出现Pandas KeyError错误。

这个问题已经有了答案:

iloc和loc有什么不同?

我有一个pandas DataFrame portfolio,其键是日期。我正在尝试通过

print(portfolio.loc[[\'2007-02-26\',\'2008-02-06\'],:])

来访问多个行,但是出现了错误

KeyError:“None of [Index([\'2007-02-26\', \'2008-02-06\'], dtype=\'object\', name=\'Date\')] are in the [index]”

但是,print(portfolio.loc[\'2007-02-26\',:])成功返回了

holdings      1094.6124
pos_diff       100.0000
cash         98905.3876
total       100000.0000
returns          0.0000
Name: 2007-02-26 00:00:00, dtype: float64

这不是一个合法的格式吗--> df.loc[[\'key1\', \'key2\', \'key3\'], \'Column1]

admin 更改状态以发布 2023年5月22日
0
0 Comments

看起来问题在于将字符串转换为时间戳的类型转换。因此,解决方法是在将标签集传递给 loc 之前明确将它们转换为 DateTime:

df = pd.DataFrame({"a" : range(5)}, index = pd.date_range("2020-01-01", freq="1D", periods=5))
print(df) 
==> 
            a
2020-01-01  0
2020-01-02  1
2020-01-03  2
2020-01-04  3
2020-01-05  4
try:
    df.loc[["2020-01-01", "2020-01-02"], :]    
except Exception as e:
    print (e) 
 ==>
"None of [Index(['2020-01-01', '2020-01-02'], dtype='object')] are in the [index]"
# But - if you convert the labels to datetime before calling loc, 
# it works fine. 
df.loc[pd.to_datetime(["2020-01-01", "2020-01-02"]), :]
===>
            a
2020-01-01  0
2020-01-02  1

0