Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将np数组中特定位置的元素放在一行中_Python_Python 3.x_Numpy - Fatal编程技术网

Python 如何将np数组中特定位置的元素放在一行中

Python 如何将np数组中特定位置的元素放在一行中,python,python-3.x,numpy,Python,Python 3.x,Numpy,我正在用Python 3.6和Numpy 1.20.1编写。问题是我有一个np.ndarray称为A,大小(10,3),还有另一个np.ndarray称为B,大小(4,3)。对于大小为3的4个数组,我想将它们放在第一个数组中的4个特定位置 例如: A = np.zeros((10, 3)) B = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) idx = [7,3,1,4] 我想把每一行按idx中的顺序放到B到A中。因此,转换后

我正在用Python 3.6和Numpy 1.20.1编写。问题是我有一个
np.ndarray
称为
A
,大小
(10,3)
,还有另一个
np.ndarray
称为
B
,大小
(4,3)
。对于大小为3的4个数组,我想将它们放在第一个数组中的4个特定位置

例如:

   A = np.zeros((10, 3))
   B = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
   idx = [7,3,1,4]
我想把每一行按idx中的顺序放到
B
A
中。因此,转换后,
A
应该如下所示:

[0, 0, 0],
[7, 8, 9],
[0, 0, 0],
[4, 5, 6],
[10, 11, 12],
[0, 0, 0],
[0, 0 ,0],
[1, 2, 3],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0].
我特别想知道是否有可能在一行代码中实现这一点


我尝试了
A[idx]=B
,但它给了我一个错误:
索引器:数组的索引太多了

您的代码对我来说运行得非常好。
至于问题,您可以尝试:

for i, row in zip(idx, B):
    A[i] = row

Numpy版本一行

A = np.zeros((10, 3)) 
B = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) 
idx = [7,3,1,4] 
                                                                                  
A[idx] = B[ np.arange(B.shape[0]) ]  # Source from B.shape


您确定该表达式会产生该错误吗?这不适合我!
a[idx] = B[[0,1,2,3]]   # Source as constants