我有一个名为new的Pandas DataFrame,其中YearMonth列的日期格式为YYYY-MM.。我想删除基于以下条件的行:如果日期超过"2020-05“。我试着使用这个:
new = new.drop(new[new.YearMonth>'2020-05'].index)但是显示语法错误"invalid token“是行不通的。
下面是一个示例DataFrame:
>>> 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发布于 2019-12-13 15:44:40
只需转换为datetime,然后将其格式化为month并对其进行子集。
from datetime import datetime as dt
new['YearMonth']=pd.to_datetime(new['YearMonth']).dt.to_period('M')
new=new[~(new['YearMonth']>'2020-05')]发布于 2019-12-13 15:05:15
我认为你需要将>改为<=的boolean indexing,这样按月比较会更好:
new = pd.DataFrame({
'YearMonth': pd.to_datetime(['2014-09', '2014-10', '2020-09', '2021-09']).to_period('m')
})
print (new)
YearMonth
0 2014-09
1 2014-10
2 2020-09
3 2021-09
df = new[new.YearMonth <= pd.Period('2020-05', freq='m')]
print (df)
YearMonth
0 2014-09
1 2014-10在最新版本的pandas中,也可以使用compare by字符串:
df = new[new.YearMonth <= '2020-05']https://stackoverflow.com/questions/59317601
复制相似问题