【问题标题】:Pandas KeyError when using .loc() [duplicate]使用 .loc() 时的 Pandas KeyError [重复]
【发布时间】:2020-10-03 16:29:04
【问题描述】:

我有一个 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]

【问题讨论】:

  • 这能回答你的问题吗? How are iloc, ix and loc different?
  • 每当我这样做时,我都会使用行标签的元组,而不是列表。也许这就是问题?在 loc 的文档中有一个 df[(row1, row2), column] 示例:pandas.pydata.org/pandas-docs/stable/reference/api/…。还有一个使用列表的示例,但在这种情况下,单个列名也在列表中......不确定它是否重要。
  • @Sushanth 根据帖子 df.loc[[] ] 是一个有效的表达式,但它没有解决我的错误
  • 您能提供示例输入吗?
  • 您应该在问题中提供df.head(7) 或者df.head(7).to_dict()

标签: python pandas dataframe


【解决方案1】:

似乎问题在于从字符串到时间戳的类型转换。因此,解决方案是将标签集显式转换为 DateTime,然后再将它们传递给loc

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

【讨论】:

  • 成功了,谢谢!但是如果我在单个日期调用 .loc() 而不使用 to_datetime(),就像我上面的例子一样,为什么它不返回返回错误?
  • 我不确定 - 但我认为它可以自动转换字符串,但不能用于字符串列表。
  • 顺便说一句 - 如果这解决了您的问题,您介意将其标记为后代接受吗?
  • 我明白了。当然,我标记了它
猜你喜欢
  • 2014-10-18
  • 2021-01-11
  • 2021-06-17
  • 2021-08-01
  • 2019-11-15
  • 1970-01-01
  • 1970-01-01
  • 2020-03-28
相关资源
最近更新 更多