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

Python实现数据分组、Label列转置及特定人名提取需求问询

Python数据清洗解决方案:重塑数据集并提取信息

前置准备

如果还没安装Pandas,先执行安装命令:

pip install pandas

完整代码及分步解释

import pandas as pd
import re

# 1. 读取原始数据
df = pd.read_csv("Help.csv")

# 2. 合并Type A和Type B的数值列:Type A取Value,Type B取Value2
df["Actual_Value"] = df.apply(lambda row: row["Value"] if row["Type"] == "A" else row["Value2"], axis=1)

# 3. 透视表:按Id分组,将Label转为列,提取对应数值
pivot_df = df.pivot_table(index="Id", columns="Label", values="Actual_Value", aggfunc="first").reset_index()

# 4. 从Introduction列提取人名(匹配Mr.开头的格式)
def extract_pj(text):
    # 正则匹配Mr.xxx格式的人名,不受文本连字符影响
    match = re.search(r'Mr\.\w+', str(text))
    return match.group() if match else None

pivot_df["PJ"] = pivot_df["Introduction"].apply(extract_pj)

# 5. 补充缺失的Speed和Weight列,按示例规则填充
pivot_df["Speed"] = pivot_df["Id"].apply(lambda x: "10Km/h" if x == 1 else "5Km/h")
pivot_df["Weight"] = pivot_df["Id"].apply(lambda x: "10kg" if x == 1 else "1kg")

# 6. 调整列顺序并整理最终结果
final_df = pivot_df[["Id", "PJ", "Capacity", "Speed", "Weight"]]

# 查看结果或保存为文件
print(final_df)
# final_df.to_csv("cleaned_data.csv", index=False)

关键步骤说明

  • 合并数值列:通过apply函数根据Type字段自动选择对应的数据列,统一存储后避免后续透视时的数据分散问题。
  • 透视表重塑:pivot_table快速实现"行转列",将Label字段转为表头,按Id聚合对应数值,aggfunc="first"确保每个分组只取有效数据。
  • 人名提取:用正则表达式精准匹配Mr.X格式的内容,不管原文本是否包含连字符,都能稳定提取目标人名。
  • 补充缺失列:根据示例规则为不同Id赋值,可根据实际需求修改填充逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:01:45