Python programming add a column of methods to the NumPy matrix example

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.