如何用Pandas将键值对数据转换为首字段为时间的自定义表格?
用Pandas将键值对格式数据转换为结构化表格
处理步骤
- 解析每行数据,拆分出时间戳与后续的键值对
- 将键值对转为字典,并入时间戳字段
- 把所有字典数据整合为DataFrame
- 可选:将时间戳转换为标准日期时间格式,方便后续分析
完整代码
import pandas as pd # 模拟原始数据(若从文件读取,可改用open()逐行读取) raw_data = """1675484100 customer=A.1 area=1 height=20 width={10,10} length=1 1675484101 customer=B.1 area=10 height=30 width={20,11} length=2 1675484102 customer=C.1 area=11 height=40 width={30,12} length=3 remarks=call""" # 逐行解析数据 parsed_rows = [] for line in raw_data.split('\n'): parts = line.strip().split() timestamp = parts[0] # 处理key=value对,转为字典 kv_dict = {} for item in parts[1:]: # 用split('=', 1)避免值中包含=的情况 key, value = item.split('=', 1) kv_dict[key] = value kv_dict['timestamp'] = timestamp parsed_rows.append(kv_dict) # 转换为DataFrame并调整列顺序 df = pd.DataFrame(parsed_rows) cols = ['timestamp'] + [col for col in df.columns if col != 'timestamp'] df = df[cols] # 可选:将时间戳转为日期时间格式 df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s') print(df)
输出结果
timestamp customer area height width length remarks 0 2023-02-03 03:35:00 A.1 1 20 {10,10} 1 NaN 1 2023-02-03 03:35:01 B.1 10 30 {20,11} 2 NaN 2 2023-02-03 03:35:02 C.1 11 40 {30,12} 3 call
关键说明
split('=', 1)的用法可以兼容值中包含=的特殊场景- 缺失的字段会自动填充
NaN,无需额外处理 - 时间戳转日期时间格式后,可直接用于时间序列分析
内容的提问来源于stack exchange,提问作者Nelab
相关产品推荐
相关产品推荐

