Home > Article > Backend Development > Numpy implements extension methods for merging multi-dimensional matrices and lists
This article mainly introduces the extension method of numpy to implement merging multi-dimensional matrices and lists. It has certain reference value. Now I share it with you. Friends in need can refer to it
1. Merge multiple numpy matrices
1. First create two multi-dimensional matrices
The size of matrix a is (2, 3, 2)
The size of matrix b is (3, 2, 3)
Use the concatentate function to merge two multi-dimensional matrices
After merging, it should be (5, 3, 2)
In [1]: import numpy as np In [2]: a = np.ndarray((3, 2, 3)) In [3]: b = np.ndarray((2, 2, 3)) In [4]: print(a.shape, b.shape) (3, 2, 3) (2, 2, 3) In [5]: c = np.concatenate((a, b), axis = 0) In [6]: print(c.shape) (5, 2, 3) In [7]:
2. Addition of matrix
The addition of matrix is Use the append function. List also has this function, but the way they are used is slightly different.
1. Create an ndarray
2, and then use the np.append() function to append (note that it is np.append, not a.append)
In [2]: import numpy as np In [3]: a = np.array([1, 2, 3, 4, 5]) In [4]: a = np.append(a, 10) In [5]: a Out[5]: array([ 1, 2, 3, 4, 5, 10]) In [6]: a = np.append(a, [1, 2, 3]) In [7]: a Out[7]: array([ 1, 2, 3, 4, 5, 10, 1, 2, 3])
3. List extension (extend)
1. The expansion of the list is to merge the two lists
2. Use the extend function
In [9]: a = [1, 2, 3, 4] In [10]: b = [5, 6, 7, 8] In [11]: a Out[11]: [1, 2, 3, 4] In [12]: b Out[12]: [5, 6, 7, 8] In [13]: c = a.extend(b) In [14]: c In [15]: a Out[15]: [1, 2, 3, 4, 5, 6, 7, 8]
Please note that the return value of the extend function is None, so the output of c in line 13 above is empty, and the value of a has changed, so it is expanded directly after a and does not have any return value.
4. Append to the list
To append the list, just use append
1. Create list a
2. Append data after a
In [28]: a = [1, 2,3,4] In [29]: a.append(6) In [30]: a Out[30]: [1, 2, 3, 4, 6] In [31]:
Related recommendations:
How to delete rows or columns in numpy.array
The above is the detailed content of Numpy implements extension methods for merging multi-dimensional matrices and lists. For more information, please follow other related articles on the PHP Chinese website!