Querying timedelta column in pandas, and filtering rows

拜拜、爱过 提交于 2019-12-01 21:47:43

问题


I have a column of timedelta in pandas. It is in the format x days 00:00:00. I want to filter out and flag the rows which have a value >=30 minutes. I have no clue how to do that using pandas. I tried booleans and if statements but it didn't work. Any help would be appreciated.


回答1:


You can convert timedeltas to seconds by total_seconds and compare with scalar:

df = df[df['col'].dt.total_seconds() < 30]

Or compare with Timedelta:

df = df[df['col'] < pd.Timedelta(30, unit='s')]

Sample:

df = pd.DataFrame({'col':pd.to_timedelta(['25:10:01','00:01:20','00:00:20'])})
print (df)
              col
0 1 days 01:10:01
1 0 days 00:01:20
2 0 days 00:00:20

df = df[df['col'].dt.total_seconds() < 30]
print (df)
       col
2 00:00:20


来源:https://stackoverflow.com/questions/48376278/querying-timedelta-column-in-pandas-and-filtering-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!