基于日期比较的Python数据帧过滤

2024-10-04 11:35:15 发布

您现在位置:Python中文网/ 问答频道 /正文

I am trying to filter my dataframe using date. The date imported from the csv is in string. hence I created a new column with the date in the 'Timestamp' format. Then I wanted to compare with a particulare date, however I am getting the following error

  • TypeError:“>;”“列表”和的实例之间不支持 “时间戳”

这是我的代码

import pandas as pd
data = [['agent_1','2019-06-27 15:35:49'],['agent_2','2029-06-27 15:35:49'],['agent_3','2019-04-27 15:35:49'],['agent_4','2029-06-27 15:35:49'],['agent_5','2019-02-27 15:35:49']]
MasterData = pd.DataFrame(data,columns=['Agents','timeCreated'])
MasterData['timeCreatedUpdated'] = pd.to_datetime(MasterData['timeCreated'],format='%Y-%m-%d %H:%M:%S')
MasterData.dtypes
datetime_object2 = pd.Timestamp(2019,8,1,12)
MasterData(['timeCreatedUpdated']>datetime_object2)

Tags: thetoinformatdatadatetimedatewith
3条回答

周一-你做的一切都对,只是在最后一行做了一个小的修正

使用

MasterData[MasterData["timeCreatedUpdated"] > datetime_object2] 

而不是

MasterData(['timeCreatedUpdated']>datetime_object2)

它为您进行主比较并返回一个布尔值(真/假),现在我们将答案再次包装在DF中以获取值

最后一行需要编辑:

MasterData[MasterData['timeCreatedUpdated']>datetime_object2]

尝试:

print(MasterData[MasterData['timeCreatedUpdated'] >pd.Timestamp(2019,8,1,12)]) 

相关问题 更多 >