python-3.x - pandas 数据帧中的跳转点 : the moment when the value in a column gets changed

标签 python-3.x pandas numpy dataframe

我正在尝试识别以下 Pandas 数据帧的跳转点。

# import Pandas library
import pandas as pd

label1 = ['422','422','422','428','428','453','453','453','453','453','421','421','421','421','421']
label2 = ['13:08','13:08','13:09','13:12','13:12','13:16','13:16','13:17','13:17','13:18','13:20','13:20','13:20','13:20','13:22']

d = {'Id':label1,'Time':label2}
df=pd.DataFrame(d)

我想找到Id值发生变化的时刻。例如,在上面的数据框中,我需要 id 422 变为 428 时的时间为 13:09,当 Id 428 变为 453 时为 13:12,当 Id 453 变为 421 时为 13:18。

非常感谢您在这方面的帮助。 see attached image showing dataframe here

最佳答案

如果Id是数字的解决方案:

首先通过diff获得差异,将第一个或最后一个 NaN 替换为 0 并用 comapre 表示不等于 - ne ,最后按 boolean indexing 过滤:

s = df.loc[df['Id'].diff().fillna(0).ne(0), 'Id']
print (s)
3     428
5     453
10    421
Name: Id, dtype: int64

df1 = df[df['Id'].diff(-1).fillna(0).ne(0)].copy()
df1['Id'] = df1['Id'].astype(str) + '-' + s.values.astype(str)
print (df1)
        Id   Time
2  422-428  13:09
4  428-453  13:12
9  453-421  13:18

另一个更通用的解决方案是通过 shift 进行比较ed 值并用 Id 列的第一个或最后一个值替换 NaN:

df1 = df[df['Id'].ne(df['Id'].shift(-1).fillna(df['Id'].values[-1]))]
print (df1)
    Id   Time
2  422  13:09
4  428  13:12
9  453  13:18

并加入Id:

s = df.loc[df['Id'].ne(df['Id'].shift().fillna(df['Id'].values[0])), 'Id']
print (s)
3     428
5     453
10    421
Name: Id, dtype: int64

df1 = df[df['Id'].ne(df['Id'].shift(-1).fillna(df['Id'].values[-1]))].copy()
df1['Id'] = df1['Id'].astype(str) + '-' + s.values.astype(str)
print (df1)
        Id   Time
2  422-428  13:09
4  428-453  13:12
9  453-421  13:18

关于python-3.x - pandas 数据帧中的跳转点 : the moment when the value in a column gets changed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51262788/

相关文章:

python - Pyautogui 查找多个屏幕截图匹配,无论颜色梯度如何

python-3.x - 如何读取ElementTree中特定子节点的文本?

python - 类型错误 : unorderable types: dict() < dict() in heapq

python - Pandas 在分组后找到中位数

python - 如何用 pandas 截断日期时间列?

python-3.x - Tensorflow 结构化数据 model.predict() 返回错误的概率

python - 用基于字典的条目数组替换 Pandas DataFrame 列中的字符串

python - 如何将 IP 转换为向量值

python - 使用polyval和polyfit在半对数图表上绘制线性回归

python - 生成所有 n 选择 k 个二元向量 python