Python(六)Numpy基本操作

(1)numpy.sum() #相加。没有axis参数表示全部相加,axis=0表示按列相加,axis=1表示按照行的方向相加.

 import numpy as np  
>>> a=np.sum([[0,1,2],[2,1,3]])  
>>> a  
9  
>>> a=np.sum([[0,1,2],[2,1,3]],axis=0)  
>>> a  
array([2, 2, 5])  
>>> a.shape  
(3,)  
>>> a=np.sum([[0,1,2],[2,1,3]],axis=1)  
>>> a  
array([3, 6])  
>>> a.shape  
(2,)  

(2)random.rand(3,3) #构造一个3*3的随机数组

In [23]:random.rand(3,3)
Out[23]: 
array([[ 0.68078538,  0.04810055,  0.89237689],
       [ 0.52380624,  0.74562381,  0.50066403],
       [ 0.57931518,  0.86270485,  0.089004  ]])

(3)mat(random.rand(3,3)) #将3*3的随机数组转化为一个3*3的矩阵

In [24]:mat(random.rand(3,3))
Out[24]: 
matrix([[ 0.11921999,  0.62176972,  0.57668133],
        [ 0.36761748,  0.32223052,  0.60415149],
        [ 0.16873549,  0.03998786,  0.33666076]])

(4)shape() #读取矩阵的长度。shape[0]就是读取矩阵第一维度的长度,shape[1]就是读取矩阵第二维度的长度。

In [26]:matDemo = mat(random.rand(3,5))
In [27]:matDemo.shape[0]
Out[27]: 3

In [28]:matDemo.shape[1]
Out[28]: 5

In [29]:shape(matDemo)
Out[29]: (3, 5)

(5)means( ) #求平均值,axis=None时计算数组中的所有值的平均值 ,axis=0时以列为单位计算数组的每列的所有值的平均值 ,axis=1时计算数组的每行为单位的所有值的平均值 ,dtype为指定数组中元素的类型,默认为float64

In [41]:a
Out[41]: 
array([[1, 2],
       [3, 4]])
In [42]:mean(a)
Out[42]: 2.5

In [43]:mean(a,axis = 0)
Out[43]: array([ 2.,  3.])

In [44]:mean(a,axis = 1)
Out[44]: array([ 1.5,  3.5])

(6)a.T #转置

In [48]:a = array([[1, 2], [3, 4]])
In [48]:a.T
Out[49]: 
array([[1, 3],
       [2, 4]])

(7)reshape() #重塑数组的维数而不改变原来的数据

In [50]: b = array([1,2,3,4,5,6,7,8])

In [51]: c = b.reshape((2,4))

In [52]: c
Out[52]: 
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])

In [53]: d = b.reshape((2,2,2))

In [54]: d
Out[54]: 
array([[[1, 2],
        [3, 4]],

       [[5, 6],
        [7, 8]]])

In [55]: e = b.reshape((3,3))  #不能改变数组原来的元素
Traceback (most recent call last):

  File "<ipython-input-55-b3c555f1a0b0>", line 1, in <module>
    e = b.reshape((3,3))

ValueError: cannot reshape array of size 8 into shape (3,3)

(8)dot() #矩阵点乘

In [58]: a = array([[1,2],[3,4]])

In [59]: b = array([[2,3],[4,5]])

In [60]: c = dot(a,b)

In [61]: c
Out[61]: 
array([[10, 13],
       [22, 29]])
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值