python - 将元素插入 numpy 数组的更好方法

标签 python arrays python-2.7 numpy scipy

我有一个 numpy 数组,并且有一个要在特定位置(不连续)插入该数组的元素列表。索引位于另一个 numpy 数组中。

target answer: [1,2,3,4,5]
original array: [1,3,5]
elements to insert: [2,4]
indices: [1,3]

numpy.insert(arr,[1,3],[2,4]) 未给出所需的结果。它给出[1,2,3,5,4]。 有什么指点吗?

最佳答案

通过 np.insert 使用范围偏移索引 -

np.insert(a, add_idx - np.arange(len(add_idx)), add_val)

示例运行 -

In [20]: a
Out[20]: array([1, 3, 5])

In [21]: add_idx
Out[21]: [1, 3]

In [22]: add_val
Out[22]: [2, 4]

In [23]: np.insert(a, add_idx - np.arange(len(add_idx)), add_val)
Out[23]: array([1, 2, 3, 4, 5])

关于python - 将元素插入 numpy 数组的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52346241/

相关文章:

javascript - Mootools 中 for (var x in data) 循环发生了什么

python - 排除 os.walk 中的特定文件夹和子文件夹

python - Python 中的相同对象问题

python - 使用 boost::python 包装 boost::optional

python - 如何删除除日期列之外所有行均为 NaN 的位置?

python - 为什么 print(copy_dic) 是 {'a' : 3}?

php - PHP:合并多维数组,按特定键分组

php 按字符串中最后一个单词的字母顺序排列数组

python - 使用 pyttsx 包时没有名为 Win32com.client 的模块错误

python - Scikit-learn的fetch不下载数据集