如何使用numpy将一个数组放到另一个数组的特定位置?

dkqlctbz  于 2022-12-23  发布在  其他
关注(0)|答案(2)|浏览(226)

我有个小问题。
例如:我有

a = [[1],[2],[3],[4],[5]]
b = numpy.zeros((8, 1))

我想得到

c = [[0],[0],[1],[2],[3],[0],[4],[5]]

我知道,在数组c中,第0、1和-3行仍然为0
其他选项,如何在特定位置添加零行,即第0、1和-3行
先谢谢你!

js81xvg6

js81xvg61#

对于常规方法,您可以尝试以下方法:

a = [[1],[2],[3],[4],[5]]
b = np.zeros((8, 1))
index = [0, 1, -3]
# convert negative index to positive index : -3 to 5
zero_indexes = np.asarray(index) % b.shape[0]
# [0, 1, -3] -> array([0, 1, 5])
all_indexes = np.arange(b.shape[0])
zero = np.isin(all_indexes, zero_indexes)
# insert 'a' to not_zero index
b[~zero] = a
print(b)

您可以使用np.insert

a = [[1],[2],[3],[4],[5]]
# ---^0--^1--^2--^3--^4
# two times insert in index : 0
# one time insert in index : 3
b = np.insert(np.asarray(a), (0, 0, 3), values=[0], axis=0)
print(b)

输出:

[[0]
 [0]
 [1]
 [2]
 [3]
 [0]
 [4]
 [5]]
yizd12fk

yizd12fk2#

您可以在b中指定要分配的索引,然后将a中的值分配给这些索引。

import numpy

a = [[1],[2],[3],[4],[5]]
b = numpy.zeros((8, 1))

# you can use your own method of determining the indices to overwrite.
# this example uses the indices specified in your question.
b_indices = [2,3,4,6,7] # indices in b to overwrite, len(b_indices) == len(a)

b[b_indices] = numpy.array(a) # overwrite specified indices in b with values from a

输出:

array([[0.],
   [0.],
   [1.],
   [2.],
   [3.],
   [0.],
   [4.],
   [5.]])

相关问题