天天看點

Python資料分析與展示:科學計算基礎庫numpy-1代碼示例

numpy 科學計算基礎庫

官方文檔:

https://docs.scipy.org/doc/numpy/user/quickstart.html 清單和數組差別

清單:資料類型可以不同
數組:資料類型相同      

N維數組對象 ndarray

dimension 次元: 一組資料的組織形式
軸axis 資料次元
秩rank 軸的數量
ndarray數組一般要求所有元素類型相同(同質),數組下标從0開始      

ndarray元素類型

布爾:bool(True False)
c語言int,環境有關: intc,intp
整數:int8,int16,int32,init64
無符号整數: uint8,uint16,uint32,uinit64
半精度浮點數:float16,float32,float64
複數:complex64,complex128(實部+j虛部)

python文法支援:整數,浮點數,複數      

ndarray對象的屬性

ndim 秩: 行向量或列向量的極大無關組中包含向量的個數
shape 尺寸n行m列
size  元素個數 n*m
dtype 元素類型
itemsize 每個元素大小      

ndarray數組建立

1、通過清單、元組建立
    array(list/tuple)

2、numpy函數建立
    arange(n) 0 ~ n-1
    ones(shape) 全1數組
    zeros(shape) 全0數組
    full(shape, val) 全val數組
    eye(n) n*n數組,對角線為1, 其餘為0
    ones_like(a) 根據a的形狀,全1數組
    zeros_like(a) 根據a的形狀,全0數組
    full_like(a, val) 根據a的形狀,全val數組
    linspase()  根據起止資料等間距填充資料
    concatenate() 合并數組

預設類型是浮點型      

ndarray數組變換

次元變換
    reshape(shape) 不改變原數組,傳回新數組
    resize(shape)  改變原數組
    swapaxes(ax1, ax2) 次元調換
    flatten() 降維,折疊為一維數組

類型變換
    astype(type) 傳回新數組
    tolist() ndarray數組轉為清單      

ndarray數組操作

索引, 切片 和python清單類似
次元之間用逗号(,),切片用冒号(:)      

ndarray數組運算

numpy一進制函數,元素級運算

    np.abs(x) np.fabs(x) 各元素絕對值 
    np.sqrt(x) 各元素平方根
    np.square(x) 各元素平方
    np.log(x) np.log10(x) np.log2(x) 各元素自然對數,10底對數,2底對數
    np.ceil(x)  np.floor(x) 各元素的取整值ceil向上, floor向下
    np.rint(x)  各元素四舍五入值
    np.modf(x)  各元素小數和整數部分拆為兩個數組
    np.cos(x) np.sin(x) np.tan(x)普通型三角函數
    np.cosh(x) np.sinh(x)  np.tanh(x) 雙曲型三角函數
    np.exp(x)  各元素指數值
    np.sign(x) 各元素符号值(1(+), 0, -1(-))

numpy二進制函數

    + - * / **  兩個數組計算
    np.maximum(x, y) np.fmax() 元素級的最大值
    np.minimum(x, y) np.fmin() 元素級的最小值
    np.mod(x, y) 元素級的模運算
    np.copysign(x, y) 将y元素符号指派給x元素
    > < >= <= == != 比較運算       

代碼示例

# -*- coding: utf-8 -*-

# @File    : numpy_demo.py
# @Date    : 2018-05-06

import numpy as np

# ndarray對象的屬性
def foo1():
    a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
    print(a)
    """
    [[1 2 3 4]
     [5 6 7 8]]
    """

    # 秩
    print(a.ndim) # 2

    # 尺寸 n行m列
    print(a.shape) # (2, 4)

    # 元素個數 n*m
    print(a.size) # 8

    # 元素類型
    print(a.dtype) # int64

    # 每個元素大小
    print(a.itemsize) # 8


# 通過清單或元組建立ndarray對象
def foo2():
    # 從清單建立
    a = np.array([1, 2, 3])
    print(type(a))
    # <class 'numpy.ndarray'>

    # 從元組建立
    b = np.array((1, 2, 3))
    print(type(b))
    # <class 'numpy.ndarray'>

    # 清單元組混合建立
    c = np.array([[1, 2, 3], (1, 2, 3)])
    print(type(c))
    print(c)
    """
    <class 'numpy.ndarray'>
    [[1 2 3]
     [1 2 3]]
    """

# 通過numpy函數建立ndarray對象
def foo3():
    # 指定範圍
    a = np.arange(10)
    print(a)
    # [0 1 2 3 4 5 6 7 8 9]

    # 全1數組
    b = np.ones((3, 4), dtype=np.int32)
    print(b)
    """
    [[1 1 1 1]
     [1 1 1 1]
     [1 1 1 1]]
    """

    # 全0數組
    c = np.zeros((3, 4), dtype=np.int32)
    print(c)
    """
    [[0 0 0 0]
     [0 0 0 0]
     [0 0 0 0]]
    """

    # n*n數組,對角線為1, 其餘為0
    d = np.eye(5, dtype=np.int32)
    print(d)
    """
    [[1 0 0 0 0]
     [0 1 0 0 0]
     [0 0 1 0 0]
     [0 0 0 1 0]
     [0 0 0 0 1]]
    """
    # 全值數組
    e = np.full((3, 4), 5)
    print(e)
    """
    [[5 5 5 5]
     [5 5 5 5]
     [5 5 5 5]]
    """

    # 根據起止資料等間距填充資料
    f = np.linspace(1, 10, 4, dtype=np.int32)
    print(f)
    # [ 1  4  7 10]

    # 合并數組
    g = np.array([1, 2, 3], dtype=np.int32)
    h = np.array([4, 5, 6], dtype=np.int32)
    j = np.concatenate((g, h))
    print(j)
    # [1 2 3 4 5 6]


# ndarray數組變換
def foo4():
    a = np.ones((3, 4), dtype=np.int)
    print(a)
    """
    [[1 1 1 1]
     [1 1 1 1]
     [1 1 1 1]]
    """
    print(a.ndim)  # 2

    # 不改變原數組,傳回新數組
    b = a.reshape((2, 6))
    print(b)
    """
    [[1 1 1 1 1 1]
     [1 1 1 1 1 1]]
    """

    # 改變原數組
    a.resize((6, 2))
    print(a)
    """
    [[1 1]
     [1 1]
     [1 1]
     [1 1]
     [1 1]
     [1 1]]
    """

    # 降維,折疊為一維數組
    c = a.flatten()
    print(c)
    # [1 1 1 1 1 1 1 1 1 1 1 1]

    # 修改類型
    d = c.astype(np.float)
    print(d)
    # [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]

    # 轉為清單
    e = c.tolist()
    print(e)
    # [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]


# 一維數組,索引和切片
def foo5():
    a = np.array([1, 2, 3, 4, 5])
    print(a[3])
    # 4

    print(a[1: 4: 1])
    # [2 3 4]

# 多元數組, 索引和切片
def foo6():
    a = np.arange(24).reshape(2, 3, 4)
    print(a)
    """
    [[[ 0  1  2  3]
      [ 4  5  6  7]
      [ 8  9 10 11]]

     [[12 13 14 15]
      [16 17 18 19]
      [20 21 22 23]]]
    """
    print(a[0, 2, 3])  # 11
    print(a[-1, -2, -3])  # 17

    print(a[:, :, ::2])
    """
    [[[ 0  2]
      [ 4  6]
      [ 8 10]]

     [[12 14]
      [16 18]
      [20 22]]]
    """

# 數組與标量之間的運算
def foo7():
    a = np.arange(24).reshape((2, 3, 4))
    print(a)
    """
    [[[ 0  1  2  3]
      [ 4  5  6  7]
      [ 8  9 10 11]]

     [[12 13 14 15]
      [16 17 18 19]
      [20 21 22 23]]]
    """
    # 計算平均值
    print(a.mean())
    # 11.5

    s = a/a.mean()
    print(s)
    """
    [[[0.         0.08695652 0.17391304 0.26086957]
      [0.34782609 0.43478261 0.52173913 0.60869565]
      [0.69565217 0.7826087  0.86956522 0.95652174]]

     [[1.04347826 1.13043478 1.2173913  1.30434783]
      [1.39130435 1.47826087 1.56521739 1.65217391]
      [1.73913043 1.82608696 1.91304348 2.        ]]]
    """

# numpy一進制函數
def foo8():
    a = np.arange(24).reshape((2, 3, 4))
    print(a)
    """
    [[[ 0  1  2  3]
      [ 4  5  6  7]
      [ 8  9 10 11]]

     [[12 13 14 15]
      [16 17 18 19]
      [20 21 22 23]]]
    """

    # 求平方
    b =  np.square(a)
    print(b)
    """
    [[[  0   1   4   9]
      [ 16  25  36  49]
      [ 64  81 100 121]]

     [[144 169 196 225]
      [256 289 324 361]
      [400 441 484 529]]]
    """


    # 開方
    c = np.sqrt(a)
    print(c)
    """
    [[[0.         1.         1.41421356 1.73205081]
      [2.         2.23606798 2.44948974 2.64575131]
      [2.82842712 3.         3.16227766 3.31662479]]

     [[3.46410162 3.60555128 3.74165739 3.87298335]
      [4.         4.12310563 4.24264069 4.35889894]
      [4.47213595 4.58257569 4.69041576 4.79583152]]]
    """

    # 分離整數和小數
    d = np.modf(c)
    print(d)
    """

    (array([[[0.        , 0.        , 0.41421356, 0.73205081],
            [0.        , 0.23606798, 0.44948974, 0.64575131],
            [0.82842712, 0.        , 0.16227766, 0.31662479]],

           [[0.46410162, 0.60555128, 0.74165739, 0.87298335],
            [0.        , 0.12310563, 0.24264069, 0.35889894],
            [0.47213595, 0.58257569, 0.69041576, 0.79583152]]]), 
    array([[[0., 1., 1., 1.],
            [2., 2., 2., 2.],
            [2., 3., 3., 3.]],

           [[3., 3., 3., 3.],
            [4., 4., 4., 4.],
            [4., 4., 4., 4.]]]))
    """

# numpy二進制函數
def foo9():重點内容
    a = np.array([1, 4, 5, 8])
    b = np.array([2, 3, 6, 7])

    # 求最大值
    c = np.maximum(a, b)
    print(c)
    # [2 4 6 8]

    # 比較運算
    d = a > b
    print(d)
    # [False  True False  True]