You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对含UUT的Pandas时间序列重采样至1秒并补0以分组绘图?

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:

DateTimeUUTSentReceivedLatency(ms)Sum
2018-01-25 15:03:05uut-1114272
2018-01-25 15:03:06uut-10000
2018-01-25 15:03:07uut-10000
2018-01-25 15:03:08uut-10000
2018-01-25 15:03:09uut-10000

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 UUT before 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:41:42