Python 复制numpy数组中的行元素

Python 复制numpy数组中的行元素,python,numpy,Python,Numpy,我有一个数组X,格式为,形状为(444095) 现在我想创建一个新的numpy数组,比如说X\u train=np.empty([444095]),并以不同的顺序逐行复制。假设我想要第五排X列车的第一排X 如何做到这一点(将整行复制到一个新的numpy数组)类似于matlab?将新的行顺序定义为索引列表,然后使用以下方法定义X\u train: 请注意,与Matlab不同,Python使用基于0的索引,因此第5行有索引4 还要注意,整数索引(由于它能够以任意顺序选择值)返回原始NumPy数组的副

我有一个数组
X
,格式为
,形状为
(444095)

现在我想创建一个新的numpy数组,比如说
X\u train=np.empty([444095])
,并以不同的顺序逐行复制。假设我想要第五排
X
列车
的第一排
X


如何做到这一点(将整行复制到一个新的numpy数组)类似于matlab?

将新的行顺序定义为索引列表,然后使用以下方法定义
X\u train

请注意,与Matlab不同,Python使用基于0的索引,因此第5行有索引4

还要注意,整数索引(由于它能够以任意顺序选择值)返回原始NumPy数组的副本


这同样适用于稀疏矩阵和NumPy数组。

Python通常通过引用工作,这是您应该记住的。你需要做的是复制一份,然后交换。我已经编写了一个交换行的演示函数

import numpy as np # import numpy

''' Function which swaps rowA with rowB '''
def swapRows(myArray, rowA, rowB):
    temp = myArray[rowA,:].copy() # create a temporary variable 
    myArray[rowA,:] = myArray[rowB,:].copy() 
    myArray[rowB,:]= temp

a = np.arange(30) # generate demo data
a = a.reshape(6,5) # reshape the data into 6x5 matrix

print a # prin the matrix before the swap
swapRows(a,0,1) # swap the rows
print a # print the matrix after the swap
要回答您的问题,一个解决方案是使用

X_train = np.empty([44, 4095])
X_train[0,:] = x[4,:].copy() # store in the 1st row the 5th one 
这个答案似乎是最符合逻辑的

亲切问候,

X_train = np.empty([44, 4095])
X_train[0,:] = x[4,:].copy() # store in the 1st row the 5th one