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