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

问题描述 投票:0回答:2

我试图根据传感器的类型,将传感器数据的时间戳四舍五入到最接近的5分钟。我有一列叫做 "传感器类型",有两个选项:"空气 "或 "声音"。"空气 "或 "声音"。对于传感器类型 "空气",时间戳应该四舍五入到最接近的5分钟。传感器类型为声音的时间戳应该保持不变。

有了这个规则,所有的时间戳都四舍五入到5分钟,这样就可以了。

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

在下面的掩码中,所有空气的传感器类型都被选中。

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

实际上,我应该结合这两条规则来得到我想要的东西。然而,我无法管理这如何工作。下面的规则给出了一个错误 "TypeError: 不支持用DataFrame索引系列,请使用适当的DataFrame列"。

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

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

dtypes:
timestamp        datetime64[ns]
sensor type              object

希望有人能帮助我,如何能把这两行结合起来。

python data-mining pandas time
2个回答
1
投票

除了前面的答案,你也可以尝试下面的答案。

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

enter image description here


0
投票

既然你想为每个人做一些也许有点不同的事情,那么你就应该为每个人做一些不同的事情。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
© www.soinside.com 2019 - 2024. All rights reserved.