我正在尝试识别以下 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/