我有一组采用以下格式的点。对于每个 Id1,都有一组 Id2 及其纬度和经度。对于 Id1 和 Id2 的每组,我需要该组中的第一条记录 除了最后一组,我需要第一条记录和最后一条记录。请参阅下面的输出。
只是想知道 pandas 有没有办法可以实现这一点。任何帮助,将不胜感激。谢谢。
Id1 Id2 Latitude Longitude
179 183 33.67 -83.24
179 183 31.33 -83.11
179 184 33.58 -83.34
179 184 33.61 -83.14
179 185 33.60 -83.54
179 185 33.60 -83.54
180 185 33.67 -83.64
180 185 33.79 -83.74
180 186 33.81 -83.84
180 186 33.81 -83.84
输出:
Id1 Id2 Latitude Longitude
179 183 33.67 -83.24
179 184 33.58 -83.34
179 185 33.60 -83.54
179 185 33.60 -83.54
179 186 33.79 -83.74
179 186 33.81 -83.84
180 185 33.67 -83.64
180 186 33.81 -83.84
180 186 33.81 -83.88
最佳答案
这个不太面向 pandas,但它使用 group-by
操作:
# Function to check if row values are equal to last_group values
def compare_to_groups(x, last_groups):
return any((x[['Id1','Id2']] == last_groups[i]).all(1).any() for i in range(len(last_groups)))
# Get the last groups
last_groups = df.groupby('Id1')['Id1','Id2'].last().values
# Apply to each group
df.groupby(['Id1','Id2']).apply(lambda x: x if compare_to_groups(x, last_groups) else x.head(1)).reset_index(drop=True)
它应该产生:
Id1 Id2 Latitude Longitude
0 179 183 33.67 -83.24
1 179 184 33.58 -83.34
2 179 185 33.60 -83.54
3 179 185 33.60 -83.54
4 180 185 33.67 -83.64
5 180 186 33.81 -83.84
6 180 186 33.81 -83.84
我希望这会有所帮助。
关于python - 按 pandas 数据框中的数据分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41146726/