python - 我想根据每个 deviceId 过滤行并对这些行执行一些操作。 ( Pandas )

标签 python pandas

我想检查 test_date_time 列中的时间间隙:

device_id           eventDateTime      firstPacketDateTime  lastPacketDateTime  test_date_time
MC2C5HRC0KF445779   27/12/2021 0:45    27/12/2021 0:45      27/12/2021 0:59     0:45
MC2C5HRC0KF445779   27/12/2021 1:00    27/12/2021 1:00      27/12/2021 1:13     1:00
MC2C5HRC0KF445779   27/12/2021 1:15    27/12/2021 1:16      27/12/2021 1:29     1:15
MC2C5HRC0KF445779   27/12/2021 1:30    27/12/2021 1:30      27/12/2021 1:42     1:30
MC2H3JRC0LC178168   27/12/2021 10:45   27/12/2021 10:46     27/12/2021 10:56    10:45
MC2H3JRC0LC178168   27/12/2021 11:15   27/12/2021 11:15     27/12/2021 11:25    11:15
MC2H3JRC0LC178168   27/12/2021 11:30   27/12/2021 11:35     27/12/2021 11:35    11:30

时间应该从 0:00 增加到 23:45,列的每个索引都有一个间隔为 15 分钟的值。例如:

test_date_time
0:00
0:15
0:30
0:45
1:00
1:15
1:30

我想分离出那些时间间隔超过 15 分钟的行并将它们存储在另一个数据帧中。

如何在不使用 for 循环的情况下实现此目的?

最佳答案

df = pd.read_csv(r"C:\...\input.csv")

# Creating new column with the type casted times
df["test_dt"] = pd.to_timedelta(df['test_date_time']+":00")

# Another new column with just the difference of the consecutive values
df["delta_test_dt"] = df["test_dt"].diff()

# Now creating a timedelta object for the 15 minutes gap
delta = pd.to_timedelta("15m")

# Filtering the dataframe
new_df = df[df["delta_test_dt"] > delta]

引用号:https://pandas.pydata.org/docs/reference/api/pandas.to_timedelta.html

这会将第 4 行和第 5 行存储在新数据框中(从 0 开始索引)。

关于python - 我想根据每个 deviceId 过滤行并对这些行执行一些操作。 ( Pandas ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70562193/

相关文章:

python - 将带有时间戳的 Pandas 数据框转换为字符串

python - 使用 Python 精确替换内容中的单词

Python Mechanize 模块,选择表单中的所有输入字段

python - 大量的multiprocessing.Process导致死锁

pandas - 如何只裁剪一列数据框

python - Pandas 拆分列字符串并绘制唯一值

python - 当您不知道您的对象是否可迭代时如何迭代

python - Django ModelChoiceField 查询集的自定义顺序

python - 为什么 loc 和 iloc 对 pandas DataFrame 的行进行切片的工作方式不同?

Python 请求 : Allow more retries