Python numpy:将一个numpy数组的元素添加到另一个初始化为指定位置的数组的元素

问题描述 投票:0回答:2

假设我们有一个由 numpy 零数组组成的 numpy 数组

arr1=np.zeros((len(Train),(L))

其中 Train 是固定长度整数数组的(数据集)numpy 数组。 我们还有另一个 1d numpy 数组,positions 长度为 len(Train).

现在我们希望在 Train 指定的位置添加 arr1positions 的元素。

一种方法是在 Train 数组上使用 for 循环,如下所示:

k=len(Train[0])
for i in range(len(Train)):
    arr1[i,int(positions[i]):int((positions[i]+k))]=Train[i,0:k])]

但是,使用显式 for 循环遍历整个 Train 集很慢,我想对其进行优化。

python numpy numpy-ndarray numpy-slicing
2个回答
0
投票

您可以使用numpy的高级索引将Train的元素添加到arr1的指定位置。这是实现此目的的示例代码:

# Example data
Train = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
positions = np.array([1, 3, 0])
L = 6
arr1 = np.zeros((len(Train), L))

# Compute the indices for advanced indexing
start_indices = np.arange(len(Train)).reshape(-1, 1)
offsets = np.arange(L)
indices = start_indices + positions.reshape(-1, 1) + offsets.reshape(1, -1)

# Add the elements of Train to arr1 at the specified positions
arr1[np.unravel_index(indices, arr1.shape)] += Train.reshape(-1)

# Print the result
print(arr1)

在此代码中,我们首先使用 np.arange 为 Train 的每一行创建一系列索引来计算高级索引的索引,并添加指定的位置和偏移量以创建最终索引数组。然后,我们使用这些索引使用高级索引将 Train 的元素添加到 arr1 中的适当位置。

结果是一个 numpy 数组 arr1,其中 Train 的元素已添加到位置指定的适当位置。


0
投票

这是生成所有要分配给的索引的方法。设置:

import numpy as np

n = 12   # Number of training samples
l = 8    # Number of columns in the output array
k = 4    # Number of columns in the training samples

arr       = np.zeros((n, l), dtype=int)
train     = np.random.randint(10, size=(n, k))
positions = np.random.randint(l - k, size=n)

随机示例数据:

>>> train
array([[3, 4, 3, 2],
       [3, 6, 4, 1],
       [0, 7, 9, 6],
       [4, 0, 4, 8],
       [2, 2, 6, 2],
       [4, 5, 1, 7],
       [5, 4, 4, 4],
       [0, 8, 5, 3],
       [2, 9, 3, 3],
       [3, 3, 7, 9],
       [8, 9, 4, 8],
       [8, 7, 6, 4]])
>>> positions
array([3, 2, 3, 2, 0, 1, 2, 2, 3, 2, 1, 1])

带有广播技巧的高级索引:

rows = np.arange(n)[:, None]             # Shape (n, 1)
cols = np.arange(k) + positions[:, None] # Shape (n, k)
arr[rows, cols] = train

输出:

>>> arr
array([[0, 0, 0, 3, 4, 3, 2, 0],
       [0, 0, 3, 6, 4, 1, 0, 0],
       [0, 0, 0, 0, 7, 9, 6, 0],
       [0, 0, 4, 0, 4, 8, 0, 0],
       [2, 2, 6, 2, 0, 0, 0, 0],
       [0, 4, 5, 1, 7, 0, 0, 0],
       [0, 0, 5, 4, 4, 4, 0, 0],
       [0, 0, 0, 8, 5, 3, 0, 0],
       [0, 0, 0, 2, 9, 3, 3, 0],
       [0, 0, 3, 3, 7, 9, 0, 0],
       [0, 8, 9, 4, 8, 0, 0, 0],
       [0, 8, 7, 6, 4, 0, 0, 0]])
© www.soinside.com 2019 - 2024. All rights reserved.