如何对含UUT的Pandas时间序列重采样至1秒并补0以分组绘图?
Resample Time Series to 1-Second Intervals and Plot UUT Trends
Got it, let's walk through how to handle your time series resampling and plotting task step by step using pandas and matplotlib. Here's a complete solution:
Step 1: Import Required Libraries
First, we'll need pandas for data manipulation and matplotlib for plotting:
import pandas as pd import matplotlib.pyplot as plt
Step 2: Load and Prepare the Raw Data
We'll start by loading your provided data into a pandas DataFrame and converting the DateTime column to a proper datetime type:
# Raw data as a string (you can also load this from a CSV file directly) raw_data = """DateTime UUT Sent Received Latency(ms) Sum 2018-01-25 15:03:05 uut-1 1 1 427 2 2018-01-25 15:03:05 uut-2 1 1 664 2 2018-01-25 15:03:17 uut-1 1 1 637 2 2018-01-25 15:03:17 uut-2 1 1 1229 2 2018-01-25 15:03:29 uut-1 1 1 1154 2 2018-01-25 15:03:29 uut-2 1 1 1148 2 2018-01-25 15:04:00 uut-1 1 1 279 2""" # Load into DataFrame df = pd.read_csv(pd.compat.StringIO(raw_data), sep='\s+') # Convert DateTime column to datetime type df['DateTime'] = pd.to_datetime(df['DateTime'])
Step 3: Resample to 1-Second Intervals
We'll create a full 1-second interval time range covering your data's start and end times, then fill missing values with 0 for each UUT:
# Generate a complete 1-second time index from the earliest to latest timestamp min_timestamp = df['DateTime'].min() max_timestamp = df['DateTime'].max() full_time_index = pd.date_range(start=min_timestamp, end=max_timestamp, freq='1S') # Process each UUT group separately resampled_data = [] for uut_id, group in df.groupby('UUT'): # Set DateTime as the index for resampling group_indexed = group.set_index('DateTime') # Reindex to the full 1-second timeline, filling missing values with 0 resampled_group = group_indexed.reindex(full_time_index, fill_value=0) # Add back the UUT column (since it gets dropped during reindex) resampled_group['UUT'] = uut_id # Reset index to get DateTime back as a column resampled_data.append(resampled_group.reset_index().rename(columns={'index': 'DateTime'})) # Combine all resampled UUT data into one DataFrame final_resampled_df = pd.concat(resampled_data, ignore_index=True)
Sample Output of Resampled Data
Here's how the first 5 rows for uut-1 look after resampling:
| DateTime | UUT | Sent | Received | Latency(ms) | Sum |
|---|---|---|---|---|---|
| 2018-01-25 15:03:05 | uut-1 | 1 | 1 | 427 | 2 |
| 2018-01-25 15:03:06 | uut-1 | 0 | 0 | 0 | 0 |
| 2018-01-25 15:03:07 | uut-1 | 0 | 0 | 0 | 0 |
| 2018-01-25 15:03:08 | uut-1 | 0 | 0 | 0 | 0 |
| 2018-01-25 15:03:09 | uut-1 | 0 | 0 | 0 | 0 |
Step 4: Plot Trends by UUT
We'll create subplots for each metric (Sent, Received, Latency(ms)) to compare trends across UUTs:
# Set a clean plotting style plt.style.use('seaborn-v0_8') # Create a figure with 3 subplots (one for each metric) fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(12, 15)) axes = axes.flatten() # Define which columns to plot metrics = ['Sent', 'Received', 'Latency(ms)'] # Plot each metric for ax_idx, metric in enumerate(metrics): for uut_id, group in final_resampled_df.groupby('UUT'): axes[ax_idx].plot(group['DateTime'], group[metric], label=uut_id, linewidth=2) # Customize the plot axes[ax_idx].set_title(f'Time vs {metric}', fontsize=14) axes[ax_idx].set_xlabel('DateTime', fontsize=12) axes[ax_idx].set_ylabel(metric, fontsize=12) axes[ax_idx].legend(fontsize=10) axes[ax_idx].tick_params(axis='x', rotation=45) # Adjust layout to prevent overlapping labels plt.tight_layout() plt.show()
Key Notes
- The resampling ensures every 1-second interval is present, with non-UUT columns filled to 0 where there's no original data.
- Grouping by
UUTbefore plotting lets you easily compare each device's performance over time. - The subplot layout keeps each metric's trend clear and easy to interpret.
内容的提问来源于stack exchange,提问作者user97662
相关产品推荐
相关产品推荐

