Numpy教程(4)

2017-11-16  本文已影响0人  孙宏志

Numpy基本操作

ndarray-数组与标量、数组之间的运算

image.png

数组与数组之间的运算:

形状与形状必须一致。


image.png

ndarray-数组的矩阵积

矩阵:多维数组即矩阵。

矩阵积(matrix product):两个二维矩阵(行和列的矩阵)满足第一个矩阵的列数与第二个矩阵的行数相同,那么可以进行矩阵的乘法,即矩阵积,矩阵积不是元素级的运算。也称为点积、数量积。


image.png
image.png

ndarray-多维数组的索引

image.png

Numpy中通过切片得到的新数组,只是原来数组的一个视图,因此对新数组的操作也会影响原来的数组


image.png
A =np.random.random((4,4))
print(A.shape)
A
image.png
B = A<0.5         #B数组为A种每个元素是否小于0.5 的布尔值
print(B.shape)
B                 # 打印B数组
image.png
C = A[B]             # 将B数组中True的值取出来形成一个新的数组,这个前提条件是A的shape和B的shape是要一致的。
print(C.shape)
C                    # A数组元素在B中对应为True的元素组成的新的数组

![image.png](https://img.haomeiwen.com/i6353508/06ed9dd6b73ce47b.png?imageM[图片上传中...(image.png-ed63f-1511880880297-0)]
ogr2/auto-orient/strip%7CimageView2/2/w/1240)

下图是一个通过数组的方式获取学生成绩的例子


image.png

reshape 函数的作用在于重新定义数组的形状
reshape(-1,)的作用将取得的数组转为一维数组


image.png
image.png

对于一维数组来说,加不加reshape(-1,)没有太大的区别


image.png

注意图中运用了C = A[B] 的方法获取内容,改方法的前提条件上述已经提到:A的shape和B的shape是要一致的。


image.png

ndarray-花式索引

如果仅需要取列的数据,应当参考下图第二个写法。


image.png

求第1,2,5行的0,3,2列的数据做法如下:


image.png

ndarray-数组的转置与轴对换

ndarray-通用函数/常用函数

一元函数


image.png
image.png

isnan 函数
如何声明包含nan的数组呢?
使用np.NaN

arr3=np.array([1,np.NaN,2,3])
arr3
image.png

np.isnan函数的使用

image.png
image.png

各个函数使用示例

image.png

ndarray-通用函数、常用函数(二元函数)


image.png
arr1 = np.array([1,2,8,1])
arr2 = np.array([4,2,6,0])

print("np.mod(arr2,arr1)=",np.mod(arr2,arr1))
print("np.dot(arr1,arr2)=",np.dot(arr1,arr2))
print("arr1 > arr2",np.greater(arr1,arr2))
print("arr1 >= arr2",np.greater_equal(arr1,arr2))
print("arr1 < arr2", np.less(arr1,arr2))
print("arr1 == arr2", np.equal(arr1,arr2))
print("arr1 != arr2", np.not_equal(arr1,arr2))
print("np.logical_and(arr1,arr2)=",np.logical_and(arr1,arr2))
print("np.logical_or(arr1,arr2)=",np.logical_or(arr1,arr2))
print("np.logical_xor(arr1,arr2)=",np.logical_xor(arr1,arr2))
image.png

ndarray-聚合函数

arr = np.array([[1,2,3,4],[7,8,9,10]])
print("arr=",arr)
print("min=",arr.min())
print("max=",arr.max())
print("mean=",arr.mean())
print("std=",arr.std())
print("根据方差公式计算的方差值为:", np.sqrt(np.power(arr-arr.mean(),2).sum()/arr.size))
image.png image.png

np.where函数

help(np.where)

Help on built-in function where in module numpy.core.multiarray:

where(...)
    where(condition, [x, y])
    
    Return elements, either from `x` or `y`, depending on `condition`.
    
    If only `condition` is given, return ``condition.nonzero()``.
    
    Parameters
    ----------
    condition : array_like, bool
        When True, yield `x`, otherwise yield `y`.
    x, y : array_like, optional
        Values from which to choose. `x` and `y` need to have the same
        shape as `condition`.
    
    Returns
    -------
    out : ndarray or tuple of ndarrays
        If both `x` and `y` are specified, the output array contains
        elements of `x` where `condition` is True, and elements from
        `y` elsewhere.
    
        If only `condition` is given, return the tuple
        ``condition.nonzero()``, the indices where `condition` is True.
    
    See Also
    --------
    nonzero, choose
    
    Notes
    -----
    If `x` and `y` are given and input arrays are 1-D, `where` is
    equivalent to::
    
        [xv if c else yv for (c,xv,yv) in zip(condition,x,y)]
    
    Examples
    --------
    >>> np.where([[True, False], [True, True]],
    ...          [[1, 2], [3, 4]],
    ...          [[9, 8], [7, 6]])
    array([[1, 8],
           [3, 4]])
    
    >>> np.where([[0, 1], [1, 0]])
    (array([0, 1]), array([1, 0]))
    
    >>> x = np.arange(9.).reshape(3, 3)
    >>> np.where( x > 5 )
    (array([2, 2, 2]), array([0, 1, 2]))
    >>> x[np.where( x > 3.0 )]               # Note: result is 1D.
    array([ 4.,  5.,  6.,  7.,  8.])
    >>> np.where(x < 5, x, -1)               # Note: broadcasting.
    array([[ 0.,  1.,  2.],
           [ 3.,  4., -1.],
           [-1., -1., -1.]])
    
    Find the indices of elements of `x` that are in `goodvalues`.
    
    >>> goodvalues = [3, 4, 7]
    >>> ix = np.in1d(x.ravel(), goodvalues).reshape(x.shape)
    >>> ix
    array([[False, False, False],
           [ True,  True, False],
           [False,  True, False]], dtype=bool)
    >>> np.where(ix)
    (array([1, 1, 2]), array([0, 1, 1]))
image.png image.png

np.unique函数

arr2 = np.random.randint(5,13,(4,4))
print(arr2)
print()
arr3 = np.unique(arr2)
print(arr3)
image.png
上一篇 下一篇

猜你喜欢

热点阅读