Python 3.x 数据帧中的跳转点:列中的值更改的时刻
我试图确定以下数据帧的跳转点Python 3.x 数据帧中的跳转点:列中的值更改的时刻,python-3.x,pandas,numpy,dataframe,Python 3.x,Pandas,Numpy,Dataframe,我试图确定以下数据帧的跳转点 # 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'
# 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值改变的时刻。例如,在上面的数据帧中,我需要的时间为13:09,id 422变为428时为13:12,id 428变为453时为13:12,id 453变为421时为13:18
我将感谢你在这方面的帮助。
如果
Id
为数字,则解决方案:
第一个获取差值,将第一个或最后一个NaN
替换为0
,并将不相等的comapre替换为最后一个过滤器:
另一个更通用的解决方案是通过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
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
与加入的Id
:
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
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
预计会输出什么?一个只有跳转点和相关标签的数据帧。若标签1中的值是字符串而不是数字,它也会工作吗?否,所以添加了新的解决方案。