查询pandas中的timedelta列,过滤行

Posted

技术标签:

【中文标题】查询pandas中的timedelta列,过滤行【英文标题】:Querying timedelta column in pandas, and filtering rows 【发布时间】:2018-06-30 18:30:26 【问题描述】:

我在 pandas 中有一个 timedelta 列。它的格式为 x 天 00:00:00。我想过滤掉并标记值 >=30 分钟的行。我不知道如何使用熊猫来做到这一点。我尝试了布尔值和 if 语句,但没有奏效。任何帮助将不胜感激。

【问题讨论】:

【参考方案1】:

您可以通过total_secondstimedeltas 转换为秒并与标量进行比较:

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

或与Timedelta比较:

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

示例

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

【讨论】:

以上是关于查询pandas中的timedelta列,过滤行的主要内容,如果未能解决你的问题,请参考以下文章