python - 根据日期条件删除行

标签 python pandas dataframe date rows

我有一个名为 new 的 Pandas DataFrame,其中 YearMonth 列的日期格式为 YYYY-MM。我想根据条件删除行:如果日期超出“2020-05”。我尝试使用这个:

new = new.drop(new[new.YearMonth>'2020-05'].index)

但它不起作用,显示“无效 token ”语法错误。

这是一个示例数据帧:

>>> new = pd.DataFrame({
    'YearMonth': ['2014-09', '2014-10', '2020-09', '2021-09']
})
>>> print(new)
    YearMonth
0   2014-09
1   2014-10
2   2020-09
3   2021-09

放置后的预期 DataFrame 应该是:


    YearMonth
0   2014-09
1   2014-10

最佳答案

只需转换为日期时间,然后将其格式化为月份并对其进行子集化。

from datetime import datetime as dt

new['YearMonth']=pd.to_datetime(new['YearMonth']).dt.to_period('M')
new=new[~(new['YearMonth']>'2020-05')]

关于python - 根据日期条件删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59317601/

相关文章:

python - 根据属性将两个人匹配在一起

python - 如何在 seaborn lmplot 上添加标题?

python - 从 tensorflow 中的两个现有张量构造一个新张量

python - 如何在特定情况下抑制 sonarqube 规则?

pandas - 更改 Pandas 数据框中的值不起作用

python - 通过对 pandas 进行采样,用不同的元素填充数据框中的空值

python - 总结当前行与上一行的差异

python - Scrapy 异常 - exceptions.AttributeError : 'unicode' object has no attribute 'select'

python - 使用 Python 搜索 Lua 文件中的所有函数调用

python pandas : How to simplify the result of groupby ('column_name' ). count()