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

基于两列复制行并合并为单列的Pandas优化实现方法问询

Pandas DataFrame行扩展与列值重组优化方案

原始数据与需求

原始DataFrame

,resultset_id,resultsetrevision_id,injection_id,injection_acqmethod_id,injection_damethod_id
0,8c502f71-9965-43c9-b3be-e7988a2fc89e,023c8953-565e-4953-991a-a842e0444e67,5cff24fc-f1b8-43b1-98a5-39fc41c27a33,f85b0a52-52a8-4e8d-93c3-54be11c7f8c3,
1,8c502f71-9965-43c9-b3be-e7988a2fc89e,023c8953-565e-4953-991a-a842e0444e67,6c005f00-8654-4ebc-8e42-c92bd4a5fa64,53b34ff9-fec2-472d-a4d0-61e6029d586a,cd4cbbd9-5f23-4146-a499-9c90e3c73383

需求与预期结果

需将原有2行数据扩展为4行,把injection_acqmethod_id和injection_damethod_id的内容统一放入新列method_id,预期结果如下:

,resultset_id,resultsetrevision_id,injection_id,injection_acqmethod_id,injection_damethod_id,method_id
0,8c502f71-9965-43c9-b3be-e7988a2fc89e,023c8953-565e-4953-991a-a842e0444e67,5cff24fc-f1b8-43b1-98a5-39fc41c27a33,f85b0a52-52a8-4e8d-93c3-54be11c7f8c3,,f85b0a52-52a8-4e8d-93c3-54be11c7f8c3
0,8c502f71-9965-43c9-b3be-e7988a2fc89e,023c8953-565e-4953-991a-a842e0444e67,5cff24fc-f1b8-43b1-98a5-39fc41c27a33,f85b0a52-52a8-4e8d-93c3-54be11c7f8c3,,None
1,8c502f71-9965-43c9-b3be-e7988a2fc89e,023c8953-565e-4953-991a-a842e0444e67,6c005f00-8654-4ebc-8e42-c92bd4a5fa64,53b34ff9-fec2-472d-a4d0-61e6029d586a,cd4cbbd9-5f23-4146-a499-9c90e3c73383,53b34ff9-fec2-472d-a4d0-61e6029d586a
1,8c502f71-9965-43c9-b3be-e7988a2fc89e,023c8953-565e-4953-991a-a842e0444e67,6c005f00-8654-4ebc-8e42-c92bd4a5fa64,53b34ff9-fec2-472d-a4d0-61e6029d586a,cd4cbbd9-5f23-4146-a499-9c90e3c73383,cd4cbbd9-5f23-4146-a499-9c90e3c73383

用户现有实现代码

_injections["method_id"] = (_injections.injection_acqmethod_id.astype(str) + "," + _injections.injection_damethod_id.astype(str)).str.split(",")
_injections = _injections.explode("method_id")

优化实现方案

方法1:使用melt函数(最简洁直观)

melt是Pandas专为宽表转长表设计的工具,直接通过列转置实现行扩展,避免字符串拼接拆分的冗余操作:

import pandas as pd

# 指定需要转置的目标列
method_cols = ["injection_acqmethod_id", "injection_damethod_id"]
# 生成包含method_id的临时表
melted = _injections[method_cols].melt(var_name="temp_col", value_name="method_id")
# 合并原表与临时表,保留原始索引对齐数据
result = _injections.join(melted.drop("temp_col", axis=1)).reset_index(drop=True)

方法2:apply+explode(更Pythonic的列表生成)

直接从行中提取两列值生成列表,减少类型转换开销,代码可读性更强:

_injections["method_id"] = _injections.apply(
    lambda row: [row["injection_acqmethod_id"], row["injection_damethod_id"]], axis=1
)
_injections = _injections.explode("method_id")

方法3:向量化拼接(大数据集最优)

通过复制原表并分别赋值method_id,再合并结果,避免行级循环,适合大规模数据:

# 复制原表,分别将method_id设为两个目标列的值
df_acq = _injections.assign(method_id=_injections["injection_acqmethod_id"])
df_da = _injections.assign(method_id=_injections["injection_damethod_id"])
# 合并两个表并排序索引
result = pd.concat([df_acq, df_da]).sort_index().reset_index(drop=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 09:03:16