如何从含日期索引的Pandas DataFrame中移除2月29日的数据?
Pandas删除2月29日数据的报错解决
报错原因
出现TypeError: unsupported operand type(s) for &: 'int' and 'Int64Index'是因为运算符优先级问题:&(按位与)的优先级高于==,代码会先执行2 & dfr.index.day,整数和Int64Index类型无法直接用&运算,因此触发错误。
单独执行dfr.index.month==2或dfr.index.day==29能正常生成布尔索引,但组合时必须给每个条件单独加括号,确保先完成相等判断,再做逻辑与运算。
正确代码
dfr = dfr.loc[~((dfr.index.month == 2) & (dfr.index.day == 29))]
额外验证方式
可以先筛选出所有2月29日的记录,确认过滤逻辑是否正确:
# 查看待删除的2月29日数据 feb29_records = dfr.loc[(dfr.index.month == 2) & (dfr.index.day == 29)] print(feb29_records)
内容的提问来源于stack exchange,提问作者diedro
相关产品推荐
相关产品推荐

