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

Python实现遥测数据滚动存储:保留最新100条记录(含Pandas咨询)

Python实现最新100条遥测数据维护方案

方案一:使用Pandas(适合需数据分析场景)

Pandas可以轻松实现需求,同时支持后续对数据进行统计、可视化等操作。具体实现步骤如下:

  1. 初始化空DataFrame,定义好所需列;
  2. 每次收到JSON数据时,生成当前时间戳,构造单行数据追加到DataFrame;
  3. 检查数据行数,若超过100则保留最后100条(最新记录)。

代码示例:

import pandas as pd
from datetime import datetime

# 初始化空DataFrame
telemetry_df = pd.DataFrame(columns=['timestamp', 'blvel', 'load', 'pres'])

def add_telemetry_data(json_data):
    global telemetry_df
    # 生成格式化的当前时间戳
    current_ts = datetime.now().strftime("%m-%d-%Y %H:%M:%S")
    # 构造单行数据
    new_row = pd.DataFrame({
        'timestamp': [current_ts],
        'blvel': [json_data['blvel']],
        'load': [json_data['load']],
        'pres': [json_data['pres']]
    })
    # 追加到DataFrame
    telemetry_df = pd.concat([telemetry_df, new_row], ignore_index=True)
    # 仅保留最新100条
    if len(telemetry_df) > 100:
        telemetry_df = telemetry_df.tail(100)

# 测试调用
sample_json = {"blvel":12, "load":1, "pres":201}
add_telemetry_data(sample_json)

方案二:使用collections.deque(轻量高效场景)

如果不需要复杂的数据分析,仅需维护最新100条记录,推荐使用Python标准库中的deque——它支持固定长度,当新增元素超过最大长度时会自动丢弃最旧的元素,内存占用小、操作效率高。

代码示例:

from collections import deque
from datetime import datetime

# 初始化最大长度为100的双向队列
telemetry_queue = deque(maxlen=100)

def add_telemetry_data(json_data):
    current_ts = datetime.now().strftime("%m-%d-%Y %H:%M:%S")
    # 构造带时间戳的记录
    record = {
        'timestamp': current_ts,
        'blvel': json_data['blvel'],
        'load': json_data['load'],
        'pres': json_data['pres']
    }
    telemetry_queue.append(record)

# 测试调用
sample_json = {"blvel":12, "load":1, "pres":201}
add_telemetry_data(sample_json)

# 按表格格式打印数据
def print_telemetry():
    print(f"{'timestamp':<19} | {'blvel':<5} | {'load':<4} | {'pres':<4}")
    for record in telemetry_queue:
        print(f"{record['timestamp']} | {record['blvel']:>5} | {record['load']:>4} | {record['pres']:>4}")

print_telemetry()

方案选择建议

  • 若后续需要对遥测数据做统计分析、可视化,优先选择Pandas;
  • 若仅需轻量维护最新记录,追求性能和低内存占用,选择deque即可。

内容的提问来源于stack exchange,提问作者Deepika Rao

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 17:55:09