Python programming adds a column method example to the numpy matrix
- 2020-06-15 09:21:38
- OfStack
So first of all we have 1 data that is an numpy matrix for mn and now we want to be able to add 1 column to it to make it an m matrix
import numpy as np
a = 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]]
So what we're going to do is we're going to combine a, b into c
Method 1
Add rows and columns with np.c_ [] and np.r_ [], respectively
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 2
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]])
Methods 3
Use 'column_stack'
np.column_stack((a,b))
array([[ 1., 2., 3., 1.],
[ 4., 5., 6., 1.],
[ 7., 8., 9., 1.]])
conclusion
That's all for this article's example of how to program Python to add 1 column to an numpy matrix. Interested friends can continue to refer to other relevant topics in this site, if there is any deficiency, welcome to leave a message!