Python 使用groupby对列进行筛选和排序
我有这个df:Python 使用groupby对列进行筛选和排序,python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,我有这个df: Date Plate Route Speed VehiceType 0 2020-11-03 13:54:00 0660182 Route 66 32 Wagon 1 2020-11-03 13:25:03 939CH003 Route 35 24 Truck 2 2020-11-03 09:27:11 WH3457 Route 02 41 Bus
Date Plate Route Speed VehiceType
0 2020-11-03 13:54:00 0660182 Route 66 32 Wagon
1 2020-11-03 13:25:03 939CH003 Route 35 24 Truck
2 2020-11-03 09:27:11 WH3457 Route 02 41 Bus
等等。我需要相同车牌车辆之间的时间差,我很容易获得:
df.groupby('Plate').Date.diff( )
然后,我分类(否则我会在不同的日期/盘子之间有差异,这是我不需要的)并分组如下:
df2 = df.sort_values(by=['Plate', 'Date']).groupby('Plate').Date.diff().dt.total_seconds().reset_index()
index Difference (s)
0 34517 NaN
1 377539 33.0
2 119714 34.0
3 300900 765.0
我最终得到一个df(重命名一列后),如下所示:
df2 = df.sort_values(by=['Plate', 'Date']).groupby('Plate').Date.diff().dt.total_seconds().reset_index()
index Difference (s)
0 34517 NaN
1 377539 33.0
2 119714 34.0
3 300900 765.0
这不是我需要的(“index”列应该是plates)。我想要的是:
Plate Difference
0 WH3457 54.0
1 9W432T 24.0
2 947CH05 33.0
因此,该df可以通过某些过滤器的板号合并到原始df中(左上和右上)。Pandas说不能进行合并,因为“索引”列只是数字,而plate列显然是一个字符串(排序时不知何故我错过了plate对象)。
那么,我如何才能获得这个板/差df?(必须按车牌和日期排序,否则差异就没有意义了)。
我一直在努力解决这个问题,但我无法得到它。先谢谢你
编辑:
这是原始df的较大部分(对不起,西班牙语中的对齐和车辆类型):
如果希望将计算(以秒为单位的差值)放回原始数据帧,可以使用熊猫: 此外,由于
apply
函数不执行任何聚合,df2
具有与df
相同的原始行形状,因此可以使用索引
将值映射回df
,如下所示:
df2 = df.sort_values(by=['Plate', 'Date']).groupby('Plate').Date.diff().dt.total_seconds().reset_index()
index Difference (s)
0 34517 NaN
1 377539 33.0
2 119714 34.0
3 300900 765.0
df2=df.sort_值(by=['Plate','Date']).groupby('Plate').Date.diff().dt.total_seconds()
#这个
df.loc[df2.index,'diff_in_sec']=df2
#还是这个
df2.name='diff_in_sec'
合并(df2,左索引=True,右索引=True)
请尝试发布代码以创建适当的数据框,这样我们就可以测试任何可能的答案,您的答案只有3行!!我有一个问题:它标记了一个错误,说:AttributeError:'DataFrameGroupBy'对象没有属性'Date'你没有一个名为'Date'的列吗?(完全像这样)?是的,那是我的错误,很抱歉(我把西班牙语/英语列名搞混了),你的答案很好。非常感谢。