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

Pandas:如何根据另一列值动态更新目标列并优化迭代方案

高效实现Pandas按位置填充列值

需求说明

现有如下结构的DataFrame:

handle  image_src   image_position  image_src_1 image_src_2 image_src_3
0        a       img1                1         None        None        None
1        b       img2                2         None        None        None
2        c       img3                3         None        None        None

需要根据每行image_position的值,将image_src的内容填入对应的image_src_{image_position}列,转换后结果如下:

handle  image_src   image_position  image_src_1 image_src_2 image_src_3
0        a       img1                1         img1        None        None
1        b       img2                2         None        img2        None
2        c       img3                3         None        None        img3

最优实现方案

避免逐行遍历,利用Pandas/Numpy的矢量化操作实现,大幅提升效率,以下两种方法均可:

方法一:Numpy矩阵索引赋值

利用Numpy生成位置掩码,直接批量赋值:

import pandas as pd
import numpy as np

# 构造示例DataFrame(实际使用时替换为你的数据)
df = pd.DataFrame({
    'handle': ['a', 'b', 'c'],
    'image_src': ['img1', 'img2', 'img3'],
    'image_position': [1, 2, 3],
    'image_src_1': [None, None, None],
    'image_src_2': [None, None, None],
    'image_src_3': [None, None, None]
})

# 定义目标列列表
target_cols = ['image_src_1', 'image_src_2', 'image_src_3']
# 转换为0-based列索引
col_indices = df['image_position'] - 1
# 生成位置掩码矩阵:每行仅对应position的位置为True
mask = np.eye(len(target_cols))[col_indices]

# 批量赋值:掩码位置替换为image_src的值,其余保留原数据
df.loc[:, target_cols] = np.where(mask, df['image_src'].values[:, np.newaxis], df.loc[:, target_cols])

方法二:哑变量矩阵乘法

通过get_dummies生成位置哑变量,再与image_src相乘得到目标值:

import pandas as pd

# 构造示例DataFrame
df = pd.DataFrame({
    'handle': ['a', 'b', 'c'],
    'image_src': ['img1', 'img2', 'img3'],
    'image_position': [1, 2, 3],
    'image_src_1': [None, None, None],
    'image_src_2': [None, None, None],
    'image_src_3': [None, None, None]
})

# 生成位置哑变量矩阵
dummies = pd.get_dummies(df['image_position'], prefix='image_src')
# 哑变量与image_src相乘,得到对应位置的值,其余替换为None
df[dummies.columns] = dummies.mul(df['image_src'], axis=0).replace(0, None)

方案优势

两种方法均为矢量化操作,直接对整个DataFrame/数组进行批量计算,避免了逐行遍历的Python循环开销,在数据量较大时效率提升极为明显。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:01:54