基于id_easy唯一值合并列值并生成时间范围的表格处理需求
Solution Using Pandas
If you're working with Python, pandas makes this data aggregation task straightforward. Here's a step-by-step implementation tailored to your needs:
First, let's define your sample input data:
import pandas as pd # Sample input data matching your original table 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' ], 'id_easy': [22, 22, 22, 16], 'lat/long': [ '(44.9484, 7.7728)', '(44.9503, 7.7748)', '(44.9503, 7.7748)', '(45.0314, 7.6181)' ] } df = pd.DataFrame(data)
Next, process the data to generate your target output:
# Convert Timestamp column to datetime format for easy time manipulation df['Timestamp'] = pd.to_datetime(df['Timestamp']) # Group rows by id_easy and compute the required aggregated values result = df.groupby('id_easy').agg( # Create timestamp range from earliest to latest time in the group Timestamp_range=('Timestamp', lambda x: f"{x.min().time()}-{x.max().time()}"), # Combine all lat/long entries into a single comma-separated string lat_long_combined=('lat/long', lambda x: ','.join(x)) ).reset_index() # Reorder and rename columns to match your target table structure result = result[['Timestamp_range', 'id_easy', 'lat_long_combined']] result.columns = ['Timestamp', 'id_easy', 'lat/long'] # Print the final result print(result)
Final Output:
| Timestamp | id_easy | lat/long |
|---|---|---|
| 06:31:05-06:31:05 | 16 | (45.0314, 7.6181) |
| 08:18:46-08:28:09 | 22 | (44.9484, 7.7728),(44.9503, 7.7748),(44.9503, 7.7748) |
Key Details:
- Datetime Conversion: Parsing the
Timestampcolumn into datetime objects lets us easily extract the time component and find the earliest/latest times for each group. - Group Aggregation: Using
groupby('id_easy')ensures we process all rows belonging to the same ID together. The lambda functions handle creating the time range and combining lat/long values. - Column Adjustments: Reordering and renaming columns ensures the final output matches your desired table format exactly.
This method scales well for larger datasets too—pandas is optimized for these kinds of grouping and aggregation operations.
内容的提问来源于stack exchange,提问作者Mamed
相关产品推荐
相关产品推荐

