pandas - 错误:删除索引值列表时“未在轴中找到”
问题描述
我试图每年从上午 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'] 在轴上找不到"
有什么建议我缺少什么吗?
解决方案
如果要从日期时间索引中删除,则需要传递日期时间。
例如
>>> 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
推荐阅读
- r - predict.lm 计算的 90% 或 95% 置信区间
- html - a:visited for docx files -- 颜色在 IE 和 Chrome 中不会改变
- sql - 如何组合 2 个 SQL 查询
- node.js - 恢复为 nvm 默认版本
- c - 使用 C 代码中更新的编译器工具链摆脱“表达式必须是常量值”
- python - Pandas 删除重复项的行为不符合预期
- ruby-on-rails - 在同一个 Bucket 中过滤两个数据 Searchkick Ruby on Rails
- powerbi - DAX 计算 - 最近 2 天的 SUM 销售额
- c - 如何在我的 C 限制下检查用户的有效输入?
- ios - 从多个 Mac 编译 iOS 应用程序