Python numpy生成矩阵、串联矩阵代码分享

yipeiwu_com5年前Python基础

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

python生成1行四列全2矩阵

print np.ones((1,4))*2

总结

以上就是本文关于Python numpy生成矩阵、串联矩阵代码分享的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

python列表与元组详解实例

在这章中引入了数据结构的概念。数据结构是通过某种方式组织在一起的数据元素的集合。在python中,最基本的数据结构就是序列。序列中的每个元素被分配一个序号,即元素的位置,也被称为索引。注...

python计算n的阶乘的方法代码

整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,0的阶乘为1。即:n!=1×2×3×...×n。 首先导入math模块,然后调用factorial()函数来计算阶...

Pytorch中的VGG实现修改最后一层FC

https://discuss.pytorch.org/t/how-to-modify-the-final-fc-layer-based-on-the-torch-model/766/1...

Python编程深度学习计算库之numpy

Python编程深度学习计算库之numpy

NumPy是python下的计算库,被非常广泛地应用,尤其是近来的深度学习的推广。在这篇文章中,将会介绍使用numpy进行一些最为基础的计算。 NumPy vs SciPy NumPy和...

python list多级排序知识点总结

在python3的sorted中去掉了cmp参数,转而推荐“key+lambda”的方式来排序。 如果需要对python的list进行多级排序。有如下的数据: list_num =...