Home > Backend Development > PHP Tutorial > Python programming example of adding a column to a numpy matrix

Python programming example of adding a column to a numpy matrix

小云云
Release: 2023-03-17 19:14:01
Original
2455 people have browsed it

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]]
Copy after login


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.]])
Copy after login


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]])
Copy after login


method Three

Use 'column_stack'


np.column_stack((a,b))

array([[ 1., 2., 3., 1.],
    [ 4., 5., 6., 1.],
    [ 7., 8., 9., 1.]])
Copy after login


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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template