python - 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
我希望有人可以帮助我如何将两条线结合起来,
解决方案
除了较早的答案,您还可以尝试以下方法-
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')
推荐阅读
- javascript - 无法创建 notes.json 文件
- python - 如何在 pyautogui 中获取当前鼠标位置?
- reactjs - Next.js 不同的全局 css 用于不同的组件集
- javascript - 浏览器扩展清单脚本的相对文件路径
- c# - CORS:预检工作但主要请求失败
- python - 列出嵌套字典中的值 - python
- python - 如何在 vs 代码中执行在某个按键上具有特定命令的 python 程序
- javascript - 在不使用 'on' 或 'setInterval' 或 'setTimeout' 的情况下,如何更改动态生成的元素的文本
- flutter - 在圆形框装饰内添加文本小部件
- java - 如何在java中创建打印机以将xml(Ms word,PowerPoint,Excel)doc转换为pdf