我有一个名为 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/