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

如何将OSIsoft PI Config导出的CSV转换为标准Pandas DataFrame

处理OSIsoft PI Config导出的特殊CSV并转换为Pandas DataFrame

数据格式分析

你的CSV属于分段式结构,每个传感器数据块有固定标识:

  • 以*> sensor_X开头(元数据行,无实际测量值,可忽略)
  • 中间为有效数据行:传感器名称,时间戳,测量值,空列
  • 以* End Repeat...结尾(分隔行,需过滤)

解决步骤与代码

步骤1:逐行读取并筛选有效数据

常规pd.read_csv无法直接解析这种格式,先手动读取并过滤无效行:

import pandas as pd

# 初始化存储有效数据的列表
data_records = []

# 替换为你的CSV文件路径
with open("pi_export.csv", "r", encoding="utf-8") as file:
    for line in file:
        # 去除引号、首尾空格后按逗号分割
        segments = [seg.strip('"').strip() for seg in line.strip().split(',')]
        # 跳过元数据行和结束标记行
        if segments[0].startswith("*>") or segments[0] == "* End Repeat...":
            continue
        # 提取有效字段:传感器名、时间戳、测量值
        sensor_name, ts_str, value = segments[0], segments[1], segments[2]
        # 跳过空测量值的行(可选,按需调整)
        if value:
            data_records.append({
                "sensor": sensor_name,
                "timestamp": ts_str,
                "value": value
            })

步骤2:转换为结构化DataFrame并处理数据类型

将列表转为DataFrame,同时把时间戳转为日期类型、测量值转为数值类型:

# 生成初始DataFrame
raw_df = pd.DataFrame(data_records)

# 解析时间戳(适配带时区的格式,CUT为时区标识)
raw_df["timestamp"] = pd.to_datetime(raw_df["timestamp"], format="%d-%b-%y %H:%M:%S.%f %Z")

# 转换测量值为浮点型
raw_df["value"] = raw_df["value"].astype(float)

步骤3:可选:转换为宽格式(传感器作为列)

如果需要将每个传感器单独列为一列,以时间戳为索引,可使用pivot:

wide_format_df = raw_df.pivot(index="timestamp", columns="sensor", values="value")

补充说明

  • 时区处理:如果pd.to_datetime无法自动识别CUT时区,可借助pytz库手动转换:
    import pytz
    raw_df["timestamp"] = pd.to_datetime(raw_df["timestamp"], format="%d-%b-%y %H:%M:%S.%f %Z").dt.tz_convert(pytz.utc)
    
  • 空值处理:若存在缺失的测量值,可使用raw_df.fillna(0)填充或raw_df.dropna()删除,按需选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 15:36:18