【问题标题】:Error: "not found in axis" when droping list of index values错误:删除索引值列表时“未在轴中找到”
【发布时间】:2021-02-17 07:43:20
【问题描述】:

我试图每年从一个数据框中删除两天,该数据帧的小时值从早上 6 点到晚上 8 点,日期从 15.07 到 20.10。因此,我创建了一个列表,其中包含应删除的所有日期,如下所示:


for i in range(0,6):
    Year = 1999 + i
    drop_list.append(str(Year)+'-07-15')
    drop_list.append(str(Year)+'-07-16') 

我的数据如下所示:

data

当我现在打电话时:

y = y.drop(drop_list)

我得到: KeyError: "['1999-07-15' '1999-07-16' '2000-07-15' '2000-07-16' '2001-07-15'\n '2001-07-16' '2002 -07-15' '2002-07-16' '2003-07-15' '2003-07-16'\n '2004-07-15' '2004-07-16'] 在轴上找不到"

有什么我缺少的建议吗?

【问题讨论】:

  • 根据您的屏幕截图,您的索引似乎是一个日期时间对象,并且您正在将字符串列表传递给 df.drop。

标签: pandas


【解决方案1】:

如果要从日期时间索引中删除,则需要传递日期时间。

例如

>>> s = pd.Series([1,2,3], index=pd.to_datetime(['2020-01-01', '2020-01-02', '2020-01-03']))

>>> s
2020-01-01    1
2020-01-02    2
2020-01-03    3
dtype: int64

>>> s.drop(pd.to_datetime(['2020-01-01']))
2020-01-02    2
2020-01-03    3
dtype: int64

在您的情况下,y.drop(pd.to_datetime(drop_list)) 可能有效。未来请看https://stackoverflow.com/help/how-to-ask

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-06
    • 2014-03-14
    • 1970-01-01
    • 2014-09-19
    • 2017-08-30
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    相关资源
    最近更新 更多