Python如何将列值转为新DataFrame表头并匹配写入对应数据
实现方案
核心逻辑是利用col2是固定静态值的特性,首次运行时就锁定目标表的全部列名,后续新数据通过col2的值和动态字段名拼接,直接映射到对应列即可,不需要动态调整表结构。
具体步骤
- 初始化阶段:加载首次的原始数据,提取
col2的全部唯一值,按照{动态字段名}_{col2值}的规则拼接生成所有数据列,加上第一列Timestamp组成固定的列名列表,初始化空的目标DataFrame。 - 新数据处理阶段:每获取到一批更新数据,先创建一个和目标表列完全匹配的空行字典,按照规则取该批次的基准Timestamp值(示例中取批次第一条数据的Time值);再遍历批次内每一行数据,根据当前行的
col2值,把该行的col1、col3数值分别写入col1_{col2值}、col3_{col2值}对应的字段中。 - 追加写入:把填充完成的新行追加到目标DataFrame末尾即可。
参考代码
import pandas as pd # 首次运行初始化目标表结构 init_raw_data = [ ["timestamp1", 123, 456, 789], ["timestamp2", 7584, 4547, 6545], ["timestamp3", 8974, 1241, 2140] ] init_df = pd.DataFrame(init_raw_data, columns=["Time", "col1", "col2", "col3"]) # 生成固定列集合 static_col2_values = init_df["col2"].unique().tolist() target_columns = ["Timestamp"] for dynamic_col in ["col1", "col3"]: for col2_val in static_col2_values: target_columns.append(f"{dynamic_col}_{col2_val}") target_df = pd.DataFrame(columns=target_columns) # 处理新批次更新数据 new_batch_raw = [ ["timestamp4", 17823, 456, 10789], ["timestamp5", 758404, 4547, 65045], ["timestamp6", 89744, 1241, 14140] ] new_batch_df = pd.DataFrame(new_batch_raw, columns=["Time", "col1", "col2", "col3"]) # 填充新行 new_record = {col: None for col in target_columns} new_record["Timestamp"] = new_batch_df.iloc[0]["Time"] # 按示例规则取批次首条时间戳 for _, row in new_batch_df.iterrows(): current_col2 = row["col2"] new_record[f"col1_{current_col2}"] = row["col1"] new_record[f"col3_{current_col2}"] = row["col3"] # 追加到目标表 target_df = pd.concat([target_df, pd.DataFrame([new_record])], ignore_index=True) print(target_df)
运行后输出的结果和给出的期望输出完全一致:
Timestamp col1_456 col1_4547 col1_1241 col3_456 col3_4547 col3_1241 0 timestamp4 17823 758404 89744 10789 65045 14140
如果后续col2出现新的固定值,只需要在初始化逻辑里加上新值检测,自动补全对应列即可,现有数据的列映射逻辑不需要改动。
内容的提问来源于stack exchange,提问作者Rushi
相关产品推荐
相关产品推荐

