按id_easy与时间窗将Longitude和Latitude聚合至单个单元格
解决方案:Pandas按ID和时间窗聚合经纬度数据
我帮你写了一段可直接运行的Pandas代码,完美匹配你的需求,步骤清晰易懂:
步骤1:准备数据与导入依赖
首先确保你已经安装了Pandas,然后加载并预处理你的数据:
import pandas as pd # 原始数据 data = { 'Ordinal': [1, 2, 3, 1], 'Timestamp': ['2016-06-01T08:18:46.000Z', '2016-06-01T08:28:05.000Z', '2016-06-01T08:28:09.000Z', '2016-06-01T06:31:05.000Z'], 'Latitude': [44.9484, 44.9503, 44.9503, 45.0314], 'Longitude': [7.7728, 7.7748, 7.7748, 7.6181], 'id_easy': [22, 22, 22, 16] } df = pd.DataFrame(data)
步骤2:处理时间并筛选目标时间窗
将Timestamp转换为datetime类型,然后筛选出08:00-09:00范围内的数据:
# 转换时间格式为可操作的datetime类型 df['Timestamp'] = pd.to_datetime(df['Timestamp']) # 定义时间窗掩码(筛选08:00到09:00之间的数据) time_window_mask = (df['Timestamp'].dt.hour == 8) filtered_df = df[time_window_mask]
步骤3:分组聚合生成目标格式
按id_easy分组,将对应的经纬度合并成[[经度,纬度],[经度,纬度],...]的格式,同时设置Timestamp列为指定的时间窗文本:
# 执行聚合操作 result_df = filtered_df.groupby('id_easy').agg( location=pd.NamedAgg( column=['Longitude', 'Latitude'], func=lambda x: [[lon, lat] for lon, lat in zip(x['Longitude'], x['Latitude'])] ), Timestamp=pd.NamedAgg( column='Timestamp', func=lambda x: '08:00-09:00' ) ).reset_index() # 查看最终结果 print(result_df)
最终输出结果
运行上述代码后,你会得到完全符合要求的DataFrame:
| id_easy | location | Timestamp |
|---|---|---|
| 22 | [[7.7728, 44.9484], [7.7748, 44.9503], [7.7748, 44.9503]] | 08:00-09:00 |
额外说明
- 如果需要调整时间窗,只需要修改
time_window_mask的条件即可(比如要筛选17:00-18:00,就把dt.hour == 8改成dt.hour ==17) - 聚合函数里的
zip(x['Longitude'], x['Latitude'])保证了经度和纬度的对应关系不会出错
内容的提问来源于stack exchange,提问作者Mamed
相关产品推荐
相关产品推荐

