The following article will share with you a detailed discussion of array reshaping, merging and splitting methods in Numpy. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together
1. Array reshaping
##1.1 Convert a one-dimensional array into a two-dimensional array
This can be achieved through the reshape() function. Assume that data is a one-dimensional array array of type numpy.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), now convert it into a two-dimensional array with 2 rows and 5 columns. The code is as follows:data.reshape((2,5))
data.reshape((2,-1))
1.2 Convert a two-dimensional array to a one-dimensional array
The operation of converting a multi-dimensional array into a one-dimensional array is usually called flattening or raveling, so there are two functions that can for selection. The execution code is as follows:data.ravel() # 不会产生源数据的副本 data.flatten() # 总是返回数据的副本
2. Merging and splitting arrays
##2.1 Merging arraysnumpy provides many array merging methods. Here we only introduce the most commonly used one, the concatenate method. The code is as follows:
arr1 = np.array([[1,2,3], [4,5,6]]) arr2 = np.array([[7,8,9], [10,11,12]]) data = np.concatenate([arr1, arr2], axis=0) # axis参数指明合并的轴向,0表示按行,1表示按列
2.2 Array splitting
Only the split function is introduced herenp.split(data, [1], axis=0 )#data is the split array, [1] is the split row number or column number, axis indicates splitting by column or row (the default is 0, that is, splitting by row)
Related recommendations :
Example of unified assignment of array elements in numpyA brief discussion of several sorting methods of numpy arrays_pythonThe above is the detailed content of Detailed discussion on array reshaping, merging and splitting methods in Numpy. For more information, please follow other related articles on the PHP Chinese website!