This article mainly introduces Python programming methods to add a column to the numpy matrix. I hope it can help everyone.
First we have a numpy matrix whose data is an mn. Now we hope to add a column to it and turn it into an m(n+1) 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]]
What we have to do is combine a and b to become c
Method 1
Use np.c_[] and np.r_[] to add rows and columns 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
Use 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((a,b)) array([[ 1., 2., 3., 1.], [ 4., 5., 6., 1.], [ 7., 8., 9., 1.]])
The above content is Python programming for numpy matrix Add a list of method examples, hope it can help everyone.
Related recommendations:
Quick Start Example of Python Programming
Detailed explanation of how to sort dictionary elements in a list using Python programming
Introduction to the method of python programming to implement merge sort
The above is the detailed content of Python programming example of adding a column to a numpy matrix. For more information, please follow other related articles on the PHP Chinese website!