This article mainly introduced the Python programming to the NumPy matrix to add a column Method example, hoped can help everybody.
First we have a data is a MN numpy matrix now we want to be able to give him a column into a matrix of M (n+1)
Import NumPy as NPA = Np.array ([[[1,2,3],[4,5,6],[7,8,9]]) b = Np.ones (3) c = Np.array ([[1,2,3,1],[4,5,6,1],[7,8,9,1]]) Print (a) print (b) print (c) [[1 2 3] [4 5 6] [7 8 9]][1. 1.1.] [[1 2 3 1] [4 5 6 1] [7 8 9 1]]
All we have to do is to combine a A, B, into C.
Method One
Add rows and columns separately using np.c_[] and np.r_[]
Np.c_[a,b]array ([[1., 2., 3., 1.], [4., 5., 6., 1.], [7., 8., 9., 1.] Np.c_[a,a]array ([[1, 2, 3, 1, 2, 3], [4, 5, 6, 4, 5, 6], [7, 8, 9 , 7, 8, 9]] Np.c_[b,a]array ([[1], 1., 2., 3.],
[1., 4., 5., 6.], [1., 7., 8., 9.])
Method Two
Using Np.insert
Np.insert (A, 0, values=b, Axis=1) Array ([[1, 1, 2, 3], [1, 4, 5, 6], [1, 7, 8, 9]]) Np.insert (A, 3, values=b, Axis=1 ) Array ([[1, 2, 3, 1], [4, 5, 6, 1], [7, 8, 9, 1]])
Method Three
Use ' Column_stack '
Np.column_stack ((b)) array ([[1., 2., 3., 1.], [4., 5., 6., 1.], [7., 8., 9., 1.]
The above is Python programming to add a list of methods to the NumPy matrix example, I hope to help everyone.