Python Pandas groupby将组中一行的值添加到组中的所有行
给定一个大致如下的数据帧Python Pandas groupby将组中一行的值添加到组中的所有行,python,pandas,dataframe,group-by,pandas-groupby,Python,Pandas,Dataframe,Group By,Pandas Groupby,给定一个大致如下的数据帧df: TripID time Latitude SectorID sector_leave_time 0 42 7 52.5 5 8 1 42 8 52.6 5 8 2 42 9 52.7 6 10 3 42
df
:
TripID time Latitude SectorID sector_leave_time
0 42 7 52.5 5 8
1 42 8 52.6 5 8
2 42 9 52.7 6 10
3 42 10 52.8 6 10
4 5 9 50.1 2 10
5 5 10 50.0 2 10
6 5 11 49.9 1 12
7 5 12 49.8 1 12
我已经通过获取扇区内的最大时间戳计算了行程离开扇区的时间。现在,我想为每个行程和扇区在扇区离开时间点添加另一列纬度,因此数据帧变成:
TripID time Latitude SectorID sector_leave_time sector_leave_lat
0 42 7 52.5 5 8 52.6
1 42 8 52.6 5 8 52.6
2 42 9 52.7 6 10 52.8
3 42 10 52.8 6 10 52.8
4 5 9 50.1 2 10 50.0
5 5 10 50.0 2 10 50.0
6 5 11 49.9 1 12 49.8
7 5 12 49.8 1 12 49.8
到目前为止,我只能使用以下代码行将sector\u leave\u lat
添加到time==sector\u leave\u time
的行中,即当行程离开扇区时:
df['sector_leave_lat'] = df.groupby('TripID').apply(lambda x : x.loc[x['time'] == x['sector_leave_time'], 'Latitude']).reset_index().set_index('level_1')['Latitude']
我知道这行看起来很糟糕,我想把
section\u leave\u lat
添加到该扇区内的所有行程条目中。我有点没主意了,所以我希望有人能帮上忙。对于每个旅行扇区组合,您希望最后一个纬度,按时间排序
df['sector_leave_lat'] = df.sort_values('time').groupby(
['TripID', 'SectorID']
).transform('last')['Latitude']
outputs:
TripID time Latitude SectorID sector_leave_time test
0 42 7 52.5 5 8 52.6
1 42 8 52.6 5 8 52.6
2 42 9 52.7 6 10 52.8
3 42 10 52.8 6 10 52.8
4 5 9 50.1 2 10 50.0
5 5 10 50.0 2 10 50.0
6 5 11 49.9 1 12 49.8
7 5 12 49.8 1 12 49.8
由于样本数据已在每个行程扇区组中按时间排序,因此此处的排序可能是冗余的如果您熟悉SQL,问题就不会那么复杂:) 下面的代码应该可以做到这一点:
#Given your dataframe :
df
TripID time Latitude SectorID sector_leave_time
0 42.0 7.0 52.5 5.0 8.0
1 42.0 8.0 52.6 5.0 8.0
2 42.0 9.0 52.7 6.0 10.0
3 42.0 10.0 52.8 6.0 10.0
4 5.0 9.0 50.1 2.0 10.0
5 5.0 10.0 50.0 2.0 10.0
6 5.0 11.0 49.9 1.0 12.0
7 5.0 12.0 49.8 1.0 12.0
# Get the Latitude corresponding to time = sector_leave_time
df_max_lat = df.loc[df_merged.time==df.sector_leave_time, ['TripID', 'Latitude', 'SectorID']]
# Then you have :
TripID Latitude SectorID
1 42.0 52.6 5.0
3 42.0 52.8 6.0
5 5.0 50.0 2.0
7 5.0 49.8 1.0
# Add the max latitude to original dataframe applying a left join
pd.merge(df, df_max_lat, on=['TripID', 'SectorID'], how='left', suffixes=('','_sector_leave'))
# You're getting :
TripID time Latitude SectorID sector_leave_time Latitude_sector_leave
0 42.0 7.0 52.5 5.0 8.0 52.6
1 42.0 8.0 52.6 5.0 8.0 52.6
2 42.0 9.0 52.7 6.0 10.0 52.8
3 42.0 10.0 52.8 6.0 10.0 52.8
4 5.0 9.0 50.1 2.0 10.0 50.0
5 5.0 10.0 50.0 2.0 10.0 50.0
6 5.0 11.0 49.9 1.0 12.0 49.8
7 5.0 12.0 49.8 1.0 12.0 49.8
好了:)