Python numpy生成矩阵、串联矩阵

这篇博客介绍了使用Python的numpy库如何生成矩阵,包括numpy.array(), numpy.zeros(), numpy.ones()和numpy.eye()函数。同时,也讲解了如何串联矩阵,涉及到numpy.row_stack(), numpy.column_stack()和numpy.reshape()等方法。" 9791119,1517395,WSO2 ESB入门教程,"['SOA', 'ESB', 'Apache', '图形界面', 'WSO2']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import numpy

生成numpy矩阵的几个相关函数:

numpy.array()

numpy.zeros()

numpy.ones()

numpy.eye()


串联生成numpy矩阵的几个相关函数:

numpy.array()

numpy.row_stack()

numpy.column_stack()

numpy.reshape()




>>> import numpy
>>> numpy.eye(3)
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])
>>> numpy.zeros(3)
array([ 0.,  0.,  0.])
>>> numpy.ones(3)
array([ 1.,  1.,  1.])
>>> x1 = numpy.array((1, 2, 3))
>>> x1
array([1, 2, 3])
>>> x2 = numpy.array([4, 5, 6])
>>> x2
array([4, 5, 6])
>>> x3 = numpy.array((x1, x2))
>>> x3
array([[1, 2, 3],
       [4, 5, 6]])
>>> x4 = x3.reshape(2, 3)
>>> x4
array([[1, 2, 3],
       [4, 5, 6]])
>>> x4 = x3.reshape(3, 2)
>>> x4
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> x5 = numpy.row_stack(x1, x2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: vstack() takes exactly 1 argument (2 given)
>>> x5 = numpy.row_stack((x1, x2))
>>> x5
array([[1, 2, 3],
       [4, 5, 6]])
>>> x6 = numpy.row_stack([x1, x2])
>>> x6
array([[1, 2, 3],
       [4, 5, 6]])
>>> x7 = numpy.row_stack((x6, x2))
>>> x7
array([[1, 2, 3],
       [4, 5, 6],
       [4, 5, 6]])
>>> x7[0]
array([1, 2, 3])
>>> x7[1]
array([4, 5, 6])
>>> x7[2]
array([4, 5, 6])
>>> x8 = numpy.column_stack([x1, x2, x1, x2])
>>> x8
array([[1, 4, 1, 4],
       [2, 5, 2, 5],
       [3, 6, 3, 6]])
>>> x8[0]
array([1, 4, 1, 4])
>>> x8[1]
array([2, 5, 2, 5])
>>> x8[2]
array([3, 6, 3, 6])
>>> x8[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: index 3 is out of bounds for axis 0 with size 3
>>> x8[0][3]
4
>>>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值