Python Pandas,根据另一列中的值对日期时间进行舍入

Python Pandas, make date time rounding based on value in another column

我正在尝试根据传感器类型将传感器数据的时间戳舍入到最近的 5 分钟。我有一个名为 'sensor type' 的列,其中有两个选项:'air' 或 'sound'。对于传感器类型空气,时间戳应四舍五入到最接近的 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

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

假设你想为每个 sensor type 做一些不同的事情,你可以使用 groupby.

将它们组合在一起

给定您的示例数据,以下将时间戳全部舍入到最接近的 5 秒 时间戳(对于您的示例,秒显示的结果优于分钟):

In [1]: import pandas as pd

In [2]: 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 type' : ['sound', 'air', 'sound', 'air', 'sound']})

将时间戳转换为实际时间戳类型(默认为字符串):

In [3]: df["timestamp"] = pd.to_datetime(df.timestamp)

Groupby 传感器类型并对每个子数据帧执行舍入方法,将结果放入原始数据帧的新列中:

In [4]: df["rounded_timestamp"] = df.groupby("sensor type").transform(lambda d: d.dt.round("5s"))

如果你想在每个子数据帧上做非常具体的事情,你可以实现一个小函数而不是使用匿名 lambda 函数。

注意从 timestamprounded_timestamp 列的舍入值:

In [5]: df
Out[5]:
            timestamp sensor type   rounded_timestamp
0 2020-04-14 00:00:23       sound 2020-04-14 00:00:25
1 2020-04-14 00:00:37         air 2020-04-14 00:00:35
2 2020-04-14 00:01:01       sound 2020-04-14 00:01:00
3 2020-04-14 00:01:05         air 2020-04-14 00:01:05
4 2020-04-14 00:01:19       sound 2020-04-14 00:01:20

我假设您现在也可能拥有或创建其他列,所以我通常也会将数据帧的索引作为您的用例最重要的时间戳,因为这样您就可以访问一些强大的属性和方法pd.DateTimeIndex:

In [6]: df.set_index("rounded_timestamp", drop=True, inplace=True)

In [7]: df
Out[7]:
                                timestamp sensor type
rounded_timestamp                                  
2020-04-14 00:00:25   2020-04-14 00:00:23       sound
2020-04-14 00:00:35   2020-04-14 00:00:37         air
2020-04-14 00:01:00   2020-04-14 00:01:01       sound
2020-04-14 00:01:05   2020-04-14 00:01:05         air
2020-04-14 00:01:20   2020-04-14 00:01:19       sound

除了前面的答案你还可以试试下面-

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')