python - 使用 Pandas 进行事件搜索
问题描述
我有一个数据框,我想创建一个带有事件标签的列。如果条件为真,则事件将获得一个数字。但如果连续值是事件,我想给出相同的事件标签。你有什么主意吗?我尝试使用 .apply 和 .rolling,但没有成功。
数据框:
df = pd.DataFrame({'Signal_1' : [0,0,0,1,1,0,0,1,1,1,1,0,0,0,1,1,1,1,1]})
Signal_1 ExpectedColumn
0 0 NaN
1 0 NaN
2 0 NaN
3 1 1
4 1 1
5 0 NaN
6 0 NaN
7 1 2
8 1 2
9 1 2
10 1 2
11 0 NaN
12 0 NaN
13 0 NaN
14 1 3
15 1 3
16 1 3
17 1 3
18 1 3
解决方案
这是一种方法。首先创建 countup 标志,然后执行 cumsum。然后用 NaN 值更正它。
import pandas as pd
import numpy as np
df = pd.DataFrame({'Signal_1' : [0,0,0,1,1,0,0,1,1,1,1,0,0,0,1,1,1,1,1]})
# Only count up when the previous sample = 0, and the current sample = 1
df["shift"] = df["Signal_1"].shift(1)
df["countup"] = np.where((df["Signal_1"] == 1) & (df["shift"] == 0),1,0)
# Cumsum the countup flag and set to NaN when sample = 0
df["result"] = df["countup"].cumsum()
df["result"] = np.where(df["Signal_1"] == 0, np.NaN, df["result"] )
推荐阅读
- sql - SQL - 根据排名值更新行
- reactjs - 自动排序部分与反应接口
- sql - 驱动器规格无效以及如何使用其他服务器进行恢复
- python - 如何将某些行转换为相同的索引 - Python
- reactjs - 我应该如何删除警告“React Hook useEffect 缺少依赖项”?
- asp.net-mvc - 为什么此视图上的脚本不会运行
- java - 识别用于创建 AudioRecord 的一组有效参数
- delphi - 在 RAD Studio 中使用 ClientDataSets 的 2 个 TCombobox 父子关系的实时绑定表达式
- linear-regression - 为什么在 SPSS 多元回归中删除了一个自变量?
- php - 如何在使用 laravel 从数据库中获取数据时附加图像路径