首页 > 解决方案 > 错误:删除索引值列表时“未在轴中找到”

问题描述

我试图每年从上午 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') 

我的数据如下所示:

数据

当我现在打电话时:

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'] 在轴上找不到"

有什么建议我缺少什么吗?

标签: pandas

解决方案


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

例如

>>> 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


推荐阅读