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

如何基于索引数组克隆numpy数组元素并重复指定列值?

实现NumPy数组按索引重复指定元素

当然有办法啦!用NumPy的高级索引特性就能轻松实现你的需求,我给你分两种常见的场景来演示,你可以根据自己的实际需求选择:

场景1:在原位置重复选中元素(重复元素紧跟原元素)

比如原数组第一行是[1,4,3,5,2],选中索引1和4的元素(4和2),重复后变成[1,4,4,3,5,2,2]。

代码实现

import numpy as np

# 定义你的原数组
arr = np.array([
    [1, 4, 3, 5, 2],  # 第一行:索引1→4,索引4→2
    [6, 7, 8, 9, 10]   # 第二行:假设索引0→6,索引2→8
])

# 定义索引数组(每行对应原数组该行要重复的元素索引)
indices = np.array([[1, 4], [0, 2]])

# 1. 生成每行的原始列索引(比如第一行就是[0,1,2,3,4])
row_base_indices = np.tile(np.arange(arr.shape[1]), (arr.shape[0], 1))

# 2. 把原始索引和要重复的索引拼接起来
extended_indices = np.concatenate([row_base_indices, indices], axis=1)

# 3. 对每行的索引排序,保证重复元素紧跟在原元素后面
extended_indices.sort(axis=1)

# 4. 用扩展后的索引提取元素,得到最终结果
result = arr[np.arange(arr.shape[0])[:, None], extended_indices]

print(result)

输出结果

[[ 1  4  4  3  5  2  2]
 [ 6  6  7  8  8  9 10]]

场景2:把重复的元素放在每行末尾

比如原数组第一行重复后变成[1,4,3,5,2,4,2],这种实现更简单:

代码实现

import numpy as np

arr = np.array([
    [1, 4, 3, 5, 2],
    [6, 7, 8, 9, 10]
])
indices = np.array([[1, 4], [0, 2]])

# 1. 按行提取要重复的元素
repeated_parts = arr[np.arange(arr.shape[0])[:, None], indices]

# 2. 把原数组和重复部分拼接起来
result = np.concatenate([arr, repeated_parts], axis=1)

print(result)

输出结果

[[ 1  4  3  5  2  4  2]
 [ 6  7  8  9 10  6  8]]

关键知识点说明

这里用到了NumPy的高级索引:arr[np.arange(arr.shape[0])[:, None], indices],其中:

  • np.arange(arr.shape[0])[:, None]是把行索引转成二维数组(形状为(n_rows, 1)),这样能和索引数组(形状为(n_rows, k))的维度匹配,实现每行对应自己的索引列表提取元素。
  • 如果你的索引数组原本是Python列表,记得先转成NumPy数组(indices = np.array(your_list))再用哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:38:52