首页 > 解决方案 > Python Pandas,根据另一列中的值进行日期时间舍入

问题描述

我正在尝试根据传感器的类型在最近的 5 分钟内四舍五入传感器数据的时间戳。我有一个名为“传感器类型”的列,有两个选项:“空气”或“声音”。对于空气传感器类型,时间戳应四舍五入到最接近的 5 分钟。传感器类型声音的时间戳应保持不变。

使用此规则,所有时间戳都四舍五入到 5 分钟,这是可行的。

df['timestamp'] = df['timestamp'].dt.round('5min')

使用下面的面罩选择所有空气传感器类型。

mask = df['sensor type'] == 'air'

实际上我应该结合这两个规则来得到我想要的。但是,我无法管理它是如何工作的。下面的规则给出了一个错误“TypeError: Indexing a Series with DataFrame is not supported, use the appropriate DataFrame column”。

mask = df.loc[df['sensor type'] == 'air']

df[‘timestamp’][mask] = df[‘timestamp'][mask].dt.round('5min')

dtypes:
timestamp        datetime64[ns]
sensor type              object

我希望有人可以帮助我如何将两条线结合起来,

标签: pythondata-miningpandastime

解决方案


除了较早的答案,您还可以尝试以下方法-

import pandas as pd

df = pd.DataFrame({'timestamp' : ['2020-04-14 00:00:23', '2020-04-14 00:00:37', '2020-04-14 00:01:01', '2020-04-14 00:01:05', '2020-04-14 00:01:19'], 'sensor' : ['sound', 'air', 'sound', 'air', 'sound']})

df["timestamp"] = pd.to_datetime(df.timestamp)
df
mask = df['sensor'] == 'air'
df.loc[mask, 'timestamp'] = df.loc[mask, 'timestamp'].dt.round('5min')

在此处输入图像描述


推荐阅读