Python编程给numpy矩阵添加一列方法示例

yipeiwu_com5年前Python基础

首先我们有一个数据是一个mn的numpy矩阵现在我们希望能够进行给他加上一列变成一个m(n+1)的矩阵

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]]

我们要做的就是把a,b合起来变成c

方法一

使用np.c_[]和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.]])

方法二

使用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]])

方法三

使用'column_stack'

np.column_stack((a,b))

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

总结

以上就是本文关于Python编程给numpy矩阵添加一列方法示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出!

相关文章

python 字符串追加实例

通过一个for循环,将一个一个字符追加到字符串中: 方法一: string = '' str=u"追加字符" for i in range(len(str)): string+=...

python连接池实现示例程序

复制代码 代码如下:import socketimport Queueimport threading def worker():    while Tru...

给Python入门者的一些编程建议

Python是一种非常富有表现力的语言。它为我们提供了一个庞大的标准库和许多内置模块,帮助我们快速完成工作。然而,许多人可能会迷失在它提供的功能中,不能充分利用标准库,过度重视单行脚本,...

python连接mysql并提交mysql事务示例

复制代码 代码如下:# -*- coding: utf-8 -*-import sysimport MySQLdbreload(sys)sys.setdefaultencoding('u...

python赋值操作方法分享

一、序列赋值: x,y,z = 1,2,3 我们可以看作:x = 1,y = 2,z = 3 二、链接赋值: x = y = 1print id(x)print id(y) 大家可以看下...