【python】numpy库数组array基础、生成以及基本运算Basic Operations

1、numpy 数组基础

  • ndarray.ndim : 秩,即轴的数量或维度的数量,返回数组的为维度
  • ndarray.shape : ndarray对象的尺度,对于矩阵,n行m列
  • ndarray.size : ndarray对象元素的个数,相当于.shape中n*m的值
  • ndarray.dtype :ndarray对象的元素类型
  • ndarray.itemsize :ndarray对象中每个元素的大小,以字节为单位
>>> import numpy as np
>>> a = np.arange(15).reshape(3, 5)
>>> a
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
>>> a.shape
(3, 5)
>>> a.ndim
2
>>> a.dtype.name
'int64'
>>> a.itemsize
8
>>> a.size
15
>>> type(a)
<type 'numpy.ndarray'>
>>> b = np.array([6, 7, 8])
>>> b
array([6, 7, 8])
>>> type(b)
<type 'numpy.ndarray'>

2、数组的生产Array Creation

  • 传入list或者tuple,而不能直接传入一串数字
In [7]: import numpy as np

In [8]: a = np.array([1,2,3,4]) # RIGHT

In [9]: a
Out[9]: array([1, 2, 3, 4])

In [10]: a = np.array(1,2,3,4) # WRONG
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-10-825d27b7bfed> in <module>()
----> 1 a = np.array(1,2,3,4) # WRONG

ValueError: only 2 non-keyword arguments accepted

3、 基础运算Basic Operations
数组的基础运算支持很多基本的运算,比如数组相乘、

In [11]:  A = np.array( [[1,1],
    ...: ... [0,1]] )

In [12]: B = np.array( [[2,0],
    ...: ... [3,4]] )

In [13]: A
Out[13]:
array([[1, 1],
       [0, 1]])

In [14]: B
Out[14]:
array([[2, 0],
       [3, 4]])

In [15]: A*B  #同位置的元素之间相互运算
Out[15]:
array([[2, 0],
       [0, 4]])

In [16]: A.dot(B)   #矩阵乘法运算
Out[16]:
array([[5, 4],
       [3, 4]])

In [17]: np.dot(A,B)
Out[17]:
array([[5, 4],
       [3, 4]])

In [18]: np.add(A,B)
Out[18]:
array([[3, 1],
       [3, 5]])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值