python學習之數據分析(三):Numpy科學計算庫

一、Numpy的優勢:

1.Numpy介紹:

在這裏插入圖片描述

1.1 優勢:

  • Numpy(Numerical Python)是一個開源的Python科學計算庫,用於快速處理任意維度的數組。
  • Numpy支持常見的數組和矩陣操作。對於同樣的數值計算任務,使用Numpy比直接使用Python要簡潔的多。
  • Numpy使用ndarray對象來處理多維數組,該對象是一個快速而靈活的大數據容器。
  • Numpy是集成C / C++和Fortran代碼的工具
  • Numpy是衆多機器學習框架的基礎庫(Scipy/Pandas/scikit-learn/Tensorflow)

1.2 文檔:

  • 官方文檔: https://numpy.org/doc/
  • 中文文檔: https://www.numpy.org.cn/article/basics/python_numpy_tutorial.html

2. ndarray(任意緯度的數組)介紹:

NumPy provides an N-dimensional array type, the ndarray, which describes a collection of “items” of the same type.

NumPy提供了一個N緯數組類型ndarray, 他描述了相同類型的items的集合。

np.array對象:

numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
  • 參數說明:
    • object:任何暴露數組接口方法的對象都會返回一個數組或任何(嵌套)序列。
    • dtype:數組的所需數據類型,可選。
    • copy:默認爲true,對象是否被複制,可選。
    • order:C(按行)、F(按列)或A(任意,默認)。
    • subok:默認情況下,返回的數組被強制爲基類數組。 如果爲true,則返回子類。
    • ndmin:指定返回數組的最小維數。
語文 數學 英語 政治 體育
80 89 86 67 79
78 97 89 67 81
90 94 78 67 74
91 91 90 67 69
76 86 75 67 86
70 79 84 67 84
94 92 93 67 64
86 85 83 67 80

用ndarray進行存儲:


import numpy as np
# 創建ndarray
score = np.array([
    [80, 89, 86, 67, 79],
    [78, 97, 89, 67, 81],
    [90, 94, 78, 67, 74],
    [91, 91, 90, 67, 69],
    [76, 87, 75, 67, 86],
    [70, 79, 84, 67, 84],
    [94, 92, 93, 67, 64],
    [86, 85, 83, 67, 80]
])
# 返回結果:
score
array([[80, 89, 86, 67, 79],
       [78, 97, 89, 67, 81],
       [90, 94, 78, 67, 74],
       [91, 91, 90, 67, 69],
       [76, 87, 75, 67, 86],
       [70, 79, 84, 67, 84],
       [94, 92, 93, 67, 64],
       [86, 85, 83, 67, 80]])

使用Python列表可以存儲一維數組,通過列表的嵌套可以實現多維數組,那麼爲什麼還需要使用Numpy的ndarray呢?

3.ndarray與Python原生list運算效率對比:

import random
import time
import numpy as np


a = [random.random() for _ in range(100000000)]

t1 = time.time()
sum1=sum(a)
t2=time.time()
print(f'使用原生list表示:{t2-t1}, 結果爲:{sum1}')

b=np.array(a)
t4=time.time()
sum3=np.sum(b)
t5=time.time()
print(f'使用numpy數組表示{t5-t4}, 結果爲:{sum3}')
使用原生list表示:0.40561366081237793, 結果爲:49999948.824034154
使用numpy數組表示0.037039756774902344, 結果爲:49999948.82402478

t2-t1爲使用python自帶的求和函數消耗的時間,t5-t4爲使用numpy求和消耗的時間,結果爲:

0.923250675201416 0.2041323184967041

從中看到ndarray的計算速度要快很多,節約了時間。

機器學習的最大特點就是大量的數據運算,那麼如果沒有一個快速的解決方案,那可能現在python也在機器學習領域達不到好的效果。
在這裏插入圖片描述
Numpy專門針對ndarray的操作和運算進行了設計,所以數組的存儲效率和輸入輸出性能遠優於Python中的嵌套列表,數組越大,Numpy的優勢就越明顯。

4. ndarray的優勢:

4.1 內存塊風格

ndarray到底跟原生python列表有什麼不同呢,請看一張圖:
在這裏插入圖片描述
從圖中可以看出ndarray在存儲數據的時候,數據與數據的地址都是連續的,這樣就給使得批量操作數組元素時速度更快。

這是因爲ndarray中的所有元素的類型都是相同的,而Python列表中的元素類型是任意的,所以ndarray在存儲元素時內存可以連續,而python原生lis就t只能通過尋址方式找到下一個元素,這雖然也導致了在通用性能方面Numpy的ndarray不及Python原生list,但在科學計算中,Numpy的ndarray就可以省掉很多循環語句,代碼使用方面比Python原生list簡單的多。

4.2 ndarray支持並行化運算(向量化運算)

4.3 Numpy底層使用C語言編寫,內部解除了GIL(全局解釋器鎖),其對數組的操作速度不受Python解釋器的限制,效率遠高於純Python代碼。

二、認識N維數組-ndarray屬性:

1.ndarray的屬性

數組屬性反映了數組本身固有的信息。

屬性名字 屬性解釋
ndarray.shape 數組緯度的元組
ndarray.ndim 數組的組數
ndarray.size 數組中元素的數量
ndarray.itemsize 一個數組元素的長度(字節)
ndarray.dtype 數組元素的類型

2. ndarray的形狀:

首先創建一些數組。

# import numpy as np
# 創建以下不同形狀的數組
a = np.array([
    [1,2,3],
    [4,5,6]
])
b = np.array([1,2,3,4])
c = np.array([
    [
        [1,2,3],
        [4,5,6]
    ],
    [
        [7,8,9],
        [10,11,12]
    ]
])

# 分別打印出形狀
print(f"a的形狀爲:{a.shape}")
print(f"b的形狀爲:{b.shape}")
print(f"c的形狀爲:{c.shape}")
print("="*30)
# 分別打印出緯度:
print(f"a的緯度爲:{a.ndim}")
print(f"b的緯度爲:{b.ndim}")
print(f"c的緯度爲:{c.ndim}")
print("="*30)
# 數據類型
print(f"a的數據類型:{a.dtype}")
print("="*30)
# 元素的長度
print(f"a的元素的長度:{a.itemsize}個字節")

a的形狀爲:(2, 3)
b的形狀爲:(4,)
c的形狀爲:(2, 2, 3)
==============================
a的緯度爲:2
b的緯度爲:1
c的緯度爲:3
==============================
a的數據類型:int64
==============================
a的元素的長度:8個字節

如何理解數組的形狀:
二維數組:在這裏插入圖片描述
三維數組:
在這裏插入圖片描述

3.ndarray的類型:

type(score.dtype)
numpy.dtype

dtype是numpy.dtype類型,先看看對於數組來說都有哪些類型

|名稱|描述| 簡寫|
|-😐-😐-😐
|np.bool| 用一個字節存儲的布爾類型(True或False)| ‘b’|
|np.int8| 一個字節大小,-128 至 127| ‘i’|
|np.int16| 整數,-32768 至 32767| ‘i2’|
|np.int32| 整數,-2 31 至 2 32 -1 |‘i4’|
|np.int64| 整數,-2 63 至 2 63 - 1| ‘i8’|
|np.uint8| (常用於存儲圖片)無符號整數,0 至 255 |‘u’|
|np.uint16| 無符號整數,0 至 65535 |‘u2’|
|np.uint32| 無符號整數,0 至 2 ** 32 - 1| ‘u4’|
|np.uint64| 無符號整數,0 至 2 ** 64 - 1| ‘u8’|
|np.float16| 半精度浮點數:16位,正負號1位,指數5位,精度10位| ‘f2’|
|np.float32| 單精度浮點數:32位,正負號1位,指數8位,精度23位| ‘f4’|
|np.float64| 雙精度浮點數:64位,正負號1位,指數11位,精度52位| ‘f8’|
|np.complex64| 複數,分別用兩個32位浮點數表示實部和虛部| ‘c8’|
|np.complex128| 複數,分別用兩個64位浮點數表示實部和虛部| ‘c16’|
|np.object_| python對象| ‘O’|
|np.string_| 字符串| ‘S’|
|np.unicode_| unicode類型| ‘U’|

3.1創建數組時指定類型:

import numpy as np
a = np.array([[1, 2, 3],[4, 5, 6]], dtype=np.float32)
a.dtype
a
array([[1., 2., 3.],
       [4., 5., 6.]], dtype=float32)
b = np.array(["numpy", "python", "tensorflow"])
b.dtype
b
array(['numpy', 'python', 'tensorflow'], dtype='<U10')

三、基本操作:

1.生成數組的方法:

1.1 生成0和1的數組:

  • empty(shape[, dtype, order])
    • 生成初始化數組
    • 參數:
      • shape: 形狀
      • dtype: 數據類型
      • order: 'C’爲按C語言風格數組; 'F’爲按Fortran風格數組
ret = np.empty((4,3))
ret
array([[6.95167365e-310, 6.95167365e-310, 0.00000000e+000],
       [0.00000000e+000, 0.00000000e+000, 0.00000000e+000],
       [0.00000000e+000, 0.00000000e+000, 0.00000000e+000],
       [0.00000000e+000, 0.00000000e+000, 0.00000000e+000]])
ret[0][0]
6.9516736507106e-310
ret = np.empty((4,3), order='C')
ret
array([[6.95167365e-310, 6.95167365e-310, 0.00000000e+000],
       [0.00000000e+000, 0.00000000e+000, 0.00000000e+000],
       [0.00000000e+000, 0.00000000e+000, 0.00000000e+000],
       [0.00000000e+000, 0.00000000e+000, 0.00000000e+000]])
ret = np.empty((4,3), order='F')
ret
array([[6.95167365e-310, 0.00000000e+000, 0.00000000e+000],
       [6.95167365e-310, 0.00000000e+000, 0.00000000e+000],
       [0.00000000e+000, 0.00000000e+000, 0.00000000e+000],
       [0.00000000e+000, 0.00000000e+000, 0.00000000e+000]])
  • empty_like(prototype[, dtype, order,subok])
    • 生成初始化數組
    • 參數:
      • prototype: prototype:array類似於prototype的形狀和數據類型,定義返回數組的這些相同屬性
      • dtype: 數據類型
      • order: 'C’爲按C語言風格數組; 'F’爲按Fortran風格數組
      • subok: subok: 如果爲True,則新創建的數組將使用子類類型“a”,否則它將是基類數組。默認爲True
ret = np.empty_like([[1,2,3],[4,5,6],[7,8,9]])
ret
array([[139924806994856, 139924806994856,               0],
       [              0,               0,               0],
       [139923641112304,              33,        29433056]])

  • identity(n[, dtype])
    • 函數返回給定大小的單位數組。單位數組是主對角線元素都爲 1 的方陣。
    • 參數:
      • n: nxn的數組
      • dtype: 數據類型
ret = np.identity(10)
ret
array([[1., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 1., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 1., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 1., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 1., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]])

  • eye(N[, M, k, dtype,order])
    • 返回一個數組,對角線元素爲 1,其他位置爲0
    • 參數:
      • N: 行數
      • M: 列數(默認爲N)
      • k: 對角線的索引;
      • dtype: 數據類型;
      • order: 'C’爲按C語言風格數組; 'F’爲按Fortran風格數組
ret = np.eye(3,k=2)
ret
array([[0., 0., 1.],
       [0., 0., 0.],
       [0., 0., 0.]])

  • ones(shape[, dtype, order])
    • 返回一個全是1的數組
    • 參數:
      • shape:形狀;
      • dtype: 類型;
      • order: 風格;
ret = np.ones((3,4))
ret
array([[1., 1., 1., 1.],
       [1., 1., 1., 1.],
       [1., 1., 1., 1.]])

  • ones_like(a[, dtype, order, subok])
    • 返回與給定數組具有相同形狀和類型的數組。
      • 參數:
        • a:python數組;
        • subok: 如果爲True,則新創建的數組將使用子類類型“a”,否則它將是基類數組。默認爲True
ret = np.ones_like([[1,2,3],[4,5,6]])
ret
array([[1, 1, 1],
       [1, 1, 1]])

  • zeros(shape[, dtype, order])
    • 返回一個全是0的數組
  • zeros_like(a[, dtype, order, subok])
    • 返回一個與a形狀的全是0的數組
ret = np.zeros((4,3))
ret
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])
ret.dtype
dtype('float64')

  • full(shape, fill_value[, dtype, order])
    • 返回給定形狀和類型的新數組,並用“fill_value”填充。
  • full_like(a, fill_value[, dtype, order, subok])
    • 返回a形狀和類型的新數組,並用“fill_value”填充。
ret = np.full((3,4),6)
ret
array([[6, 6, 6, 6],
       [6, 6, 6, 6],
       [6, 6, 6, 6]])

1.2 從現有數組生成

  • array(object[, dtype, copy, order, subok, ndmin])
    • 創建np.array對象
    • 參數:
      • object: 轉換的list;
      • dtype: 數據類型;
      • copy(bool):
      • ndmin: 返回數組的最小維度
  • asarray(a[, dtype, order])
    • 將輸入轉換爲數組(淺拷貝)
  • asanyarray(a[, dtype, order]) ascontiguousarray(a[, dtype])
    • 將輸入轉換爲ndarray,但傳遞ndarray子類。
  • asmatrix(data[, dtype])
    • 將輸入解釋爲矩陣。不會複製輸入矩陣或數組。相當於“matrix(data,copy=False)”
  • copy(a[, order])
    • 深拷貝
help(np.asmatrix)
Help on function asmatrix in module numpy:

asmatrix(data, dtype=None)
    Interpret the input as a matrix.
    
    Unlike `matrix`, `asmatrix` does not make a copy if the input is already
    a matrix or an ndarray.  Equivalent to ``matrix(data, copy=False)``.
    
    Parameters
    ----------
    data : array_like
        Input data.
    dtype : data-type
       Data-type of the output matrix.
    
    Returns
    -------
    mat : matrix
        `data` interpreted as a matrix.
    
    Examples
    --------
    >>> x = np.array([[1, 2], [3, 4]])
    
    >>> m = np.asmatrix(x)
    
    >>> x[0,0] = 5
    
    >>> m
    matrix([[5, 2],
            [3, 4]])
arr = np.array(score)# 通過數組創建數組
arr
array([[80, 89, 86, 67, 79],
       [78, 97, 89, 67, 81],
       [90, 94, 78, 67, 74],
       [91, 91, 90, 67, 69],
       [76, 87, 75, 67, 86],
       [70, 79, 84, 67, 84],
       [94, 92, 93, 67, 64],
       [86, 85, 83, 67, 80]])
id(arr)
139923640735984
id(score)
139923641073136
m_arr = np.array(score, ndmin=6)  # 6維數組
m_arr
array([[[[[[80, 89, 86, 67, 79],
           [78, 97, 89, 67, 81],
           [90, 94, 78, 67, 74],
           [91, 91, 90, 67, 69],
           [76, 87, 75, 67, 86],
           [70, 79, 84, 67, 84],
           [94, 92, 93, 67, 64],
           [86, 85, 83, 67, 80]]]]]])

print(id(score))
arr1 = np.asarray(score)# 淺拷貝,是一種引用關係
print(id(arr1))
arr1
139923641073136
139923641073136





array([[80, 89, 86, 67, 79],
       [78, 97, 89, 67, 81],
       [90, 94, 78, 67, 74],
       [91, 91, 90, 67, 69],
       [76, 87, 75, 67, 86],
       [70, 79, 84, 67, 84],
       [94, 92, 93, 67, 64],
       [86, 85, 83, 67, 80]])
print(id(score))
arr2 = np.copy(score)# 深拷貝
print(id(arr2))
arr2
140703264483008
140699856995872





array([[80, 89, 86, 67, 79],
       [78, 97, 89, 67, 81],
       [90, 94, 78, 67, 74],
       [91, 91, 90, 67, 69],
       [76, 87, 75, 67, 86],
       [70, 79, 84, 67, 84],
       [94, 92, 93, 67, 64],
       [86, 85, 83, 67, 80]])

關於array和asarray的不同:

  1. 通過np.asarray方法生成的數組是一種引用的關係;
  2. 通過np.array和np.copy方法創建的數組,相當於深拷貝;

1.3 生成固定範圍的數組

  • 生成等間隔的序列: np.linspace (start, stop, num, endpoint, retstep, dtype)
    • 參數:
      • start 序列的起始值
      • stop 序列的終止值,如果endpoint爲true,該值包含於序列中
      • num 要生成的等間隔樣例數量,默認爲50
      • endpoint 序列中是否包含stop值,默認爲ture
      • retstep 如果爲true,返回樣例,以及連續數字之間的步長
      • dtype 輸出ndarray的數據類型
# 生成等間隔的數組
arr10 = np.linspace(-10,10,10, retstep=True, endpoint=False, dtype=np.int8)
arr10
(array([-10,  -8,  -6,  -4,  -2,   0,   2,   4,   6,   8], dtype=int8), 2.0)
arr10[0].dtype
dtype('int8')
  • 其它的還有
    • numpy.arange(start,stop, step, dtype)
      • 返回給定間隔內的等間距值。
    • numpy.logspace(start,stop, num, endpoint, base, dtype)
      • 返回在對數刻度上均勻分佈的數字。
np.arange(-10, 10, 3)
array([-10,  -7,  -4,  -1,   2,   5,   8])
import matplotlib.pyplot as plt
%matplotlib inline
N = 10
x1 = np.logspace(0.1, 1, N, endpoint=True)
x2 = np.logspace(0.1, 1, N, endpoint=False)
y = np.zeros(N)
plt.plot(x1, y, 'o')
plt.plot(x2, y + 0.5, 'o')
plt.ylim([-0.5, 1])
plt.show()

在這裏插入圖片描述

help(np.logspace)
Help on function logspace in module numpy:

logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0)
    Return numbers spaced evenly on a log scale.
    
    In linear space, the sequence starts at ``base ** start``
    (`base` to the power of `start`) and ends with ``base ** stop``
    (see `endpoint` below).
    
    .. versionchanged:: 1.16.0
        Non-scalar `start` and `stop` are now supported.
    
    Parameters
    ----------
    start : array_like
        ``base ** start`` is the starting value of the sequence.
    stop : array_like
        ``base ** stop`` is the final value of the sequence, unless `endpoint`
        is False.  In that case, ``num + 1`` values are spaced over the
        interval in log-space, of which all but the last (a sequence of
        length `num`) are returned.
    num : integer, optional
        Number of samples to generate.  Default is 50.
    endpoint : boolean, optional
        If true, `stop` is the last sample. Otherwise, it is not included.
        Default is True.
    base : float, optional
        The base of the log space. The step size between the elements in
        ``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform.
        Default is 10.0.
    dtype : dtype
        The type of the output array.  If `dtype` is not given, infer the data
        type from the other input arguments.
    axis : int, optional
        The axis in the result to store the samples.  Relevant only if start
        or stop are array-like.  By default (0), the samples will be along a
        new axis inserted at the beginning. Use -1 to get an axis at the end.
    
        .. versionadded:: 1.16.0
    
    
    Returns
    -------
    samples : ndarray
        `num` samples, equally spaced on a log scale.
    
    See Also
    --------
    arange : Similar to linspace, with the step size specified instead of the
             number of samples. Note that, when used with a float endpoint, the
             endpoint may or may not be included.
    linspace : Similar to logspace, but with the samples uniformly distributed
               in linear space, instead of log space.
    geomspace : Similar to logspace, but with endpoints specified directly.
    
    Notes
    -----
    Logspace is equivalent to the code
    
    >>> y = np.linspace(start, stop, num=num, endpoint=endpoint)
    ... # doctest: +SKIP
    >>> power(base, y).astype(dtype)
    ... # doctest: +SKIP
    
    Examples
    --------
    >>> np.logspace(2.0, 3.0, num=4)
    array([ 100.        ,  215.443469  ,  464.15888336, 1000.        ])
    >>> np.logspace(2.0, 3.0, num=4, endpoint=False)
    array([100.        ,  177.827941  ,  316.22776602,  562.34132519])
    >>> np.logspace(2.0, 3.0, num=4, base=2.0)
    array([4.        ,  5.0396842 ,  6.34960421,  8.        ])
    
    Graphical illustration:
    
    >>> import matplotlib.pyplot as plt
    >>> N = 10
    >>> x1 = np.logspace(0.1, 1, N, endpoint=True)
    >>> x2 = np.logspace(0.1, 1, N, endpoint=False)
    >>> y = np.zeros(N)
    >>> plt.plot(x1, y, 'o')
    [<matplotlib.lines.Line2D object at 0x...>]
    >>> plt.plot(x2, y + 0.5, 'o')
    [<matplotlib.lines.Line2D object at 0x...>]
    >>> plt.ylim([-0.5, 1])
    (-0.5, 1)
    >>> plt.show()
np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
np.arange(1,10,2)
array([1, 3, 5, 7, 9])

1.4 生成隨機數組:

  • np.random模塊
    • 均勻分佈

      • np.random.rand(d0, d1, …, dn):

        • 返回[0.0,1.0)內的一組均勻分佈的數。
      • np.random.uniform(low=0.0, high=1.0, size=None)

        • 功能:從一個均勻分佈[low,high)中隨機採樣,注意定義域是左閉右開,即包含low,不包含high.

        • 參數介紹:

          • low: 採樣下界,float類型,默認值爲0;
          • high: 採樣上界,float類型,默認值爲1;
          • size: 輸出樣本數目,爲int或元組(tuple)類型,例如,size=(m,n,k), 則輸出mnk個樣本,缺省時輸出1個值。
        • 返回值:ndarray類型,其形狀和參數size中描述一致。

      • np.random.randint(low, high=None, size=None, dtype=‘l’)
        從一個均勻分佈中隨機採樣,生成一個整數或N維整數數組,取數範圍:若high不爲None時,取[low,high)之間隨機整數,否則取值[0,low)之間隨機整數。

補充:均勻分佈

均勻分佈(Uniform Distribution)是概率統計中的重要分佈之一。顧名思義,均勻,表示可能性相等的含義。

# 隨機生成0~1之間均勻分佈的數據:
[np.random.rand() for _ in range(5)]
[0.8717360633822037,
 0.6730805918633668,
 0.2108965021258361,
 0.25516887719147363,
 0.20628955869951748]
np.random.uniform(0,100, (4,3))
array([[79.57229546, 20.43212571, 23.73865166],
       [10.61309527, 82.84346586, 35.25990094],
       [97.99058517, 69.39736414, 27.19670733],
       [92.39784996, 27.16057306,  4.48291463]])

np.random.randint(0,100,(4,3))
array([[ 9, 55, 62],
       [32, 64, 79],
       [46, 78, 45],
       [14, 63, 74]])
# 生成均勻分佈的隨機數組
x1 = np.random.uniform(-1,1,100000000)
x1
array([-0.67253462, -0.18370637, -0.56145391, ..., -0.88201074,
       -0.04911583, -0.94841615])
# 畫圖看分佈情況
import matplotlib.pyplot as plt
%matplotlib inline
# 生成均勻分佈的隨機數
x1 = np.random.uniform(-1, 1, 10000)

# 畫圖看分佈狀況
# 1)創建畫布
plt.figure(figsize=(20,10), dpi=100)

# 2)繪製直方圖
plt.hist(x1, bins = 1000)

# 3)顯示圖像
plt.show()

在這裏插入圖片描述

  • 正態分佈
    • np.random.randn(d0, d1, …, dn)
      • 功能:從標準正態分佈中返回一個或多個樣本值
    • np.random.normal(loc=0.0, scale=1.0, size=None)
      • loc:float
        -此概率分佈的均值(對應着整個分佈的中心centre)
      • scale:float
        • 此概率分佈的標準差(對應於分佈的寬度,scale越大越矮胖,scale越小,越瘦高)
      • size:int or tuple of ints
        • 輸出的shape,默認爲None,只輸出一個值
    • np.random.standard_normal(size=None)
      • 返回指定形狀的標準正態分佈的數組。

補充:正態分佈:

  1. 什麼是正態分佈
    正態分佈是一種概率分佈。正態分佈是具有兩個參數μ和σ的連續型隨機變量的分佈,第一參數μ是服從正態分佈的隨機變量的均值,第二個參數σ是此隨機變量的方差,所以正態分佈記作N(μ,σ )。在這裏插入圖片描述

  2. 正態分佈的應用
    生活、生產與科學實驗中很多隨機變量的概率分佈都可以近似地用正態分佈來描述。

  3. 正態分佈特點
    μ決定了其位置,其標準差σ。決定了分佈的幅度。當μ = 0,σ = 1時的正態分佈是標準正態分佈。
    在這裏插入圖片描述
    標準差如何來?

    3.1 方差
    在概率論和統計學中衡量一組數據離散程度的度量

在這裏插入圖片描述
其中M爲平均值,n爲數據總個數,S爲標準差,S^2可以理解一個整體爲方差
在這裏插入圖片描述
3.2 標準差與方差的意義
可以理解成數據的一個離散程度的衡量
在這裏插入圖片描述

[np.random.randn() for _ in range(5)] # 服從標準正態分佈的數組
[-0.042331059480765966,
 0.8361717974339892,
 -1.2577532588023523,
 0.45687321088835925,
 0.3171956800877781]
data = np.random.normal(size=1000000,)
data
array([-0.98450065, -0.2229803 , -0.85738908, ...,  2.48742035,
       -0.50831292,  1.27754532])
# 正態分佈繪圖
import matplotlib.pyplot as plt
z1 = np.random.normal(loc=10, scale=5, size=1000000,)# 均值爲10, 標準差爲5的正態分佈 
# 創建畫布
plt.figure(figsize=(20,8), dpi=100)

# 繪製圖像
plt.hist(z1,bins=1000)

# 顯示圖像
plt.show()

在這裏插入圖片描述

2.案例:隨機生成8x10的數組:

2.1 數據的創建

import numpy as np
# 創建符合正態分佈的8x10數據
change = np.random.normal(0, 1, (8, 10))
change
array([[-0.20439759,  2.18655066,  1.00081148, -0.78524415,  0.54983616,
         0.132582  , -0.94968901, -0.81263941, -0.92458089, -0.07849146],
       [ 0.24259823,  1.02601287, -0.93447052,  1.1297538 , -0.21785088,
        -0.71903282,  0.53183759,  0.15430805,  0.22148237,  1.4355278 ],
       [ 1.7726767 , -0.21472632, -0.28218712, -0.44522535,  1.67689693,
        -0.66957872, -0.9668918 , -0.15910578, -1.46497273,  0.48457951],
       [-1.28180122,  0.29404085,  0.09230369,  0.02150004,  0.775104  ,
        -0.44805295, -1.12461215,  0.33175708, -1.05580122, -1.14539542],
       [-0.4120266 ,  0.57247872, -0.70541154, -1.0781004 ,  0.93831695,
         0.94669188,  1.3258231 ,  0.74412721,  0.76481105,  0.58490424],
       [ 0.61584258,  1.05646408, -0.00728139, -1.29969934, -0.32241833,
        -1.76556109,  0.94521513, -0.44770975, -1.17634745,  1.53609323],
       [ 1.71807786, -0.69353725,  1.5894029 ,  0.25992939,  0.44398414,
         0.74716372, -1.27504794, -0.79011085,  1.9557806 ,  1.35406829],
       [-0.60579009, -0.04458717, -0.79361992,  0.04436359, -2.0980827 ,
        -0.08406398,  1.93485624, -1.00171973,  0.46025373, -1.08019521]])

2.2 數組的索引、切片

  • 獲取第一組前3列
# 二維數組,兩個維度
change[0,:3]
array([-0.20439759,  2.18655066,  1.00081148])
  • 一維,二維,三維的數組如何索引?
# 創建一個三維數組
a1 = np.array([[[1,2,3],[4,5,6]], [[7,8,9],[10,11,12]]])
# 返回結果
a1
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [10, 11, 12]]])
a1.shape
(2, 2, 3)
# 索引切片
a1[0][1]
array([4, 5, 6])
a1[0,0]
array([1, 2, 3])
a1[0,0,0]
1

2.3 形狀修改:

需求:讓剛纔的數據行列互換

ndarray.reshape(shape[, order]) Returns an array containing the same data with a new shape.
# 在轉換形狀的時候,一定要注意數組的元素匹配
change.reshape([4,20])# 只是將形狀進行了修改,但並沒有進行行列的轉換
array([[-0.20439759,  2.18655066,  1.00081148, -0.78524415,  0.54983616,
         0.132582  , -0.94968901, -0.81263941, -0.92458089, -0.07849146,
         0.24259823,  1.02601287, -0.93447052,  1.1297538 , -0.21785088,
        -0.71903282,  0.53183759,  0.15430805,  0.22148237,  1.4355278 ],
       [ 1.7726767 , -0.21472632, -0.28218712, -0.44522535,  1.67689693,
        -0.66957872, -0.9668918 , -0.15910578, -1.46497273,  0.48457951,
        -1.28180122,  0.29404085,  0.09230369,  0.02150004,  0.775104  ,
        -0.44805295, -1.12461215,  0.33175708, -1.05580122, -1.14539542],
       [-0.4120266 ,  0.57247872, -0.70541154, -1.0781004 ,  0.93831695,
         0.94669188,  1.3258231 ,  0.74412721,  0.76481105,  0.58490424,
         0.61584258,  1.05646408, -0.00728139, -1.29969934, -0.32241833,
        -1.76556109,  0.94521513, -0.44770975, -1.17634745,  1.53609323],
       [ 1.71807786, -0.69353725,  1.5894029 ,  0.25992939,  0.44398414,
         0.74716372, -1.27504794, -0.79011085,  1.9557806 ,  1.35406829,
        -0.60579009, -0.04458717, -0.79361992,  0.04436359, -2.0980827 ,
        -0.08406398,  1.93485624, -1.00171973,  0.46025373, -1.08019521]])
  • -1的運用,表示形狀元組的某個數待定
change.reshape([-1,20])#數組的形狀被修改爲:(4,20), -1表示通過待計算
array([[-0.67463255, -0.55682492,  0.69708131, -0.24457656, -0.17611206,
         1.7343531 , -1.00934609, -0.04617682,  0.23490594,  0.5209573 ,
        -2.53288804, -0.70125479,  0.27229745, -0.7437157 ,  0.22185573,
        -0.48016924,  1.13160573,  2.08810576,  0.11293965,  0.72550906],
       [-2.1551984 ,  1.04945943, -1.59312051,  0.23715467,  0.2361525 ,
         0.59683766,  0.60959889, -1.64476287,  0.52223835, -0.54062954,
        -1.59171521, -0.24085126, -1.05425483,  0.44928343, -0.93432316,
         1.4004979 ,  1.11495077, -0.14263201,  0.93353774, -0.98457224],
       [ 0.86783382,  0.28940623,  0.35313321,  0.59245488,  1.75645708,
         0.42745958, -2.06370614, -0.54296625, -1.99523884,  0.63804495,
        -0.80680326, -1.89558854,  1.14596888,  0.90220809, -1.30346797,
         0.85410948,  0.83407347, -1.41166988,  2.44899363, -0.41813567],
       [-0.61040967,  0.33401561,  1.10114761, -0.21234687,  0.69742632,
         1.18998884,  0.18451999,  1.38694629,  1.00423007,  0.92489462,
         1.2569829 ,  1.18458192, -0.77109934, -0.50750022,  0.29354087,
        -1.55762194, -1.03905661,  0.58256928, -0.28058944, -0.661335  ]])
  • ndarray.T 數組的轉置
    • 將數組的行、列進行互換
change.shape
(8, 10)
change.T.shape
(10, 8)
# 創建一個三維數組
a1 = np.array([[[1,2,3],[4,5,6]], [[7,8,9],[10,11,12]]])
# 返回結果
a1
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [10, 11, 12]]])

a1.T
array([[[ 1,  7],
        [ 4, 10]],

       [[ 2,  8],
        [ 5, 11]],

       [[ 3,  9],
        [ 6, 12]]])
  • ndarray.resize(new_shape[, refcheck]) Change shape and size of array in-place.
    • 沒有返回值,直接修改原數組
change.resize([4,20])
change
array([[-0.20439759,  2.18655066,  1.00081148, -0.78524415,  0.54983616,
         0.132582  , -0.94968901, -0.81263941, -0.92458089, -0.07849146,
         0.24259823,  1.02601287, -0.93447052,  1.1297538 , -0.21785088,
        -0.71903282,  0.53183759,  0.15430805,  0.22148237,  1.4355278 ],
       [ 1.7726767 , -0.21472632, -0.28218712, -0.44522535,  1.67689693,
        -0.66957872, -0.9668918 , -0.15910578, -1.46497273,  0.48457951,
        -1.28180122,  0.29404085,  0.09230369,  0.02150004,  0.775104  ,
        -0.44805295, -1.12461215,  0.33175708, -1.05580122, -1.14539542],
       [-0.4120266 ,  0.57247872, -0.70541154, -1.0781004 ,  0.93831695,
         0.94669188,  1.3258231 ,  0.74412721,  0.76481105,  0.58490424,
         0.61584258,  1.05646408, -0.00728139, -1.29969934, -0.32241833,
        -1.76556109,  0.94521513, -0.44770975, -1.17634745,  1.53609323],
       [ 1.71807786, -0.69353725,  1.5894029 ,  0.25992939,  0.44398414,
         0.74716372, -1.27504794, -0.79011085,  1.9557806 ,  1.35406829,
        -0.60579009, -0.04458717, -0.79361992,  0.04436359, -2.0980827 ,
        -0.08406398,  1.93485624, -1.00171973,  0.46025373, -1.08019521]])

2.4 類型修改:

  • ndarray.astype(type)
c1= change.astype(np.int32)
c1.dtype
dtype('int32')
c1
array([[ 0,  2,  1,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  0,
         0,  0,  0,  1],
       [ 1,  0,  0,  0,  1,  0,  0,  0, -1,  0, -1,  0,  0,  0,  0,  0,
        -1,  0, -1, -1],
       [ 0,  0,  0, -1,  0,  0,  1,  0,  0,  0,  0,  1,  0, -1,  0, -1,
         0,  0, -1,  1],
       [ 1,  0,  1,  0,  0,  0, -1,  0,  1,  1,  0,  0,  0,  0, -2,  0,
         1, -1,  0, -1]], dtype=int32)
c1.itemsize
4
change.itemsize
8
  • ndarray.tostring([order])或者ndarray.tobytes([order]) Construct Python bytes containing the raw data bytes in the array.
    • 轉換成bytes, 將數組轉化成二進制數據,如果需要將數組存儲到本地文件中,需要轉換成字符串
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[12, 3, 34], [5, 6, 7]]])
arr.tostring()
b'\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00"\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00\x00\x00\x00\x00'
temp = np.array([[1, 2, 3, 4],[3, 4, 5, 6]])
np.unique(temp)
array([1, 2, 3, 4, 5, 6])

四、ndarray的運算:

1.邏輯判斷:

score
array([[80, 89, 86, 67, 79],
       [78, 97, 89, 67, 81],
       [90, 94, 78, 67, 74],
       [91, 91, 90, 67, 69],
       [76, 87, 75, 67, 86],
       [70, 79, 84, 67, 84],
       [94, 92, 93, 67, 64],
       [86, 85, 83, 67, 80]])
score > 80 # 條件判斷
array([[False,  True,  True, False, False],
       [False,  True,  True, False,  True],
       [ True,  True, False, False, False],
       [ True,  True,  True, False, False],
       [False,  True, False, False,  True],
       [False, False,  True, False,  True],
       [ True,  True,  True, False, False],
       [ True,  True,  True, False, False]])
# 布爾索引
a = score[score > 80] # 將ture位置的數據拿出來
a[0] = 100
a
array([100,  86,  97,  89,  81,  90,  94,  91,  91,  90,  87,  86,  84,
        84,  94,  92,  93,  86,  85,  83])
score
array([[80, 89, 86, 60, 60],
       [60, 97, 89, 60, 81],
       [90, 94, 60, 60, 60],
       [91, 91, 90, 60, 60],
       [60, 87, 60, 60, 86],
       [60, 60, 84, 60, 84],
       [94, 92, 93, 60, 60],
       [86, 85, 83, 60, 80]])
# 布爾賦值
score[score < 80 ] = 60
score
array([[80, 89, 86, 60, 60],
       [60, 97, 89, 60, 81],
       [90, 94, 60, 60, 60],
       [91, 91, 90, 60, 60],
       [60, 87, 60, 60, 86],
       [60, 60, 84, 60, 84],
       [94, 92, 93, 60, 60],
       [86, 85, 83, 60, 80]])
score
array([[80, 89, 86, 60, 60],
       [60, 97, 89, 60, 81],
       [90, 94, 60, 60, 60],
       [91, 91, 90, 60, 60],
       [60, 87, 60, 60, 86],
       [60, 60, 84, 60, 84],
       [94, 92, 93, 60, 60],
       [86, 85, 83, 60, 80]])

2. 通用判斷函數:

  • np.all()
np.all(score < 0)# 所有元素都滿足條件時,返回True, 有一個不滿足就返回Flase
False
  • np.any()
np.any(score > 70 )# 有一個滿足條件的就返回True
True

3.三元運算符(np.where):

通過使用np.where能夠進行更加複雜的運算
三元運算符,滿足條件做某個操作,不滿足做另一種操作, 和if else語句類似

  • np.where():有返回值
np.where(score > 80, 1, 0) # 第二個和第三個參數,可以使整數,也可以是和要判斷的數組形狀相同的數組
array([[0, 1, 1, 0, 0],
       [0, 1, 1, 0, 1],
       [1, 1, 0, 0, 0],
       [1, 1, 1, 0, 0],
       [0, 1, 0, 0, 1],
       [0, 0, 1, 0, 1],
       [1, 1, 1, 0, 0],
       [1, 1, 1, 0, 0]])
  • 復合邏輯需要結合np.logical_and和np.logical_or使用:
    範圍操作
np.where(np.logical_and(score>60, score<70),score,0)# 與操作
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])
np.where(np.logical_or(score<70, score>80),score,0)# 或操作
array([[ 0, 89, 86, 60, 60],
       [60, 97, 89, 60, 81],
       [90, 94, 60, 60, 60],
       [91, 91, 90, 60, 60],
       [60, 87, 60, 60, 86],
       [60, 60, 84, 60, 84],
       [94, 92, 93, 60, 60],
       [86, 85, 83, 60,  0]])
np.where(np.logical_not(score>80), score,0)# 非操作
array([[80,  0,  0, 60, 60],
       [60,  0,  0, 60,  0],
       [ 0,  0, 60, 60, 60],
       [ 0,  0,  0, 60, 60],
       [60,  0, 60, 60,  0],
       [60, 60,  0, 60,  0],
       [ 0,  0,  0, 60, 60],
       [ 0,  0,  0, 60, 80]])
  • np.logical_xor()# 異或操作

4.統計運算:

4.1 統計指標:

在數據挖掘/機器學習領域,統計指標的值也是我們分析問題的一種方式。常用的指標如下:

  • min(a[, axis, out, keepdims])# 最小值
    • Return the minimum of an array or minimum along an axis.
  • max(a[, axis, out, keepdims])# 最大值
    • Return the maximum of an array or maximum along an axis.
  • median(a[, axis, out, overwrite_input, keepdims])# 中位數
    • Compute the median along the specified axis.
  • mean(a[, axis, dtype, out, keepdims])# 均值
    • Compute the arithmetic mean along the specified axis.
  • std(a[, axis, dtype, out, ddof, keepdims]) # 標準差
    • Compute the standard deviation along the specified axis.
  • var(a[, axis, dtype, out, ddof, keepdims]) # 方差
    • Compute the variance along the specified axis.

進行統計的時候,axis 軸的取值並不一定,Numpy中不同的API軸的值都不一樣,在這裏,axis 0代表列, axis 1代表行去進行統計

temp  =np.array([[1, 2, 3, 4],[3, 4, 5, 6]])
temp
array([[1, 2, 3, 4],
       [3, 4, 5, 6]])
# 接下來對於這個數據,進行一些統計運算
# [[1, 2, 3, 4],[3, 4, 5, 6]]
# 指定行 去統計
print("每行的最大值{}".format(np.max(temp, axis=1)))
# 使用min, std, mean
print("每行的最小值{}".format(np.min(temp, axis=1)))
print("每行的標準差{}".format(np.std(temp, axis=1)))
print("每行的均值{}".format(np.mean(temp, axis=1)))
每行的最大值[4 6]
每行的最小值[1 3]
每行的標準差[1.11803399 1.11803399]
每行的均值[2.5 4.5]
  • np.argmax(temp, axis=)
    • 返回沿軸的最大值的索引
  • np.argmin(temp, axis=)
    • 返回沿軸的最小值的索引

注:

  • axis: 0:按列計算;1:按行計算;
print("每行的最大值的索引{}".format(np.argmax(temp, axis=1)))
print("每列的最小值的索引{}".format(np.argmax(temp, axis=0)))
temp
每行的最大值的索引[3 3]
每列的最小值的索引[1 1 1 1]





array([[1, 2, 3, 4],
       [3, 4, 5, 6]])

五、數組間的運算:

1.數組與數的運算:(矢量化運算)

import numpy as np
arr = np.array([[1,2,3,4],[4,5,6,7]])
print(arr)
print(arr + 1)
print(arr * 2)
print(arr / 2)
[[1 2 3 4]
 [4 5 6 7]]
[[2 3 4 5]
 [5 6 7 8]]
[[ 2  4  6  8]
 [ 8 10 12 14]]
[[0.5 1.  1.5 2. ]
 [2.  2.5 3.  3.5]]

2. 數組與數組的運算:

2.1 形狀相同的運算

必須是兩個結構相同的數組纔可做運算

arr1 = np.array([[1,2,3,4], [5,6,7,8]])
arr2 = np.array([[4,5,6,7],[8,9,10,11]])
print(arr1)
print()
print(arr2)
print()
print(arr1 + arr2)
print()
print(arr1 / arr2)
print()
arr1 * arr2
[[1 2 3 4]
 [5 6 7 8]]

[[ 4  5  6  7]
 [ 8  9 10 11]]

[[ 5  7  9 11]
 [13 15 17 19]]

[[0.25       0.4        0.5        0.57142857]
 [0.625      0.66666667 0.7        0.72727273]]






array([[ 4, 10, 18, 28],
       [40, 54, 70, 88]])
import numpy as np
arr3 = np.array([[1,2,3,4,5,6,7,8,9], [10,11,12,13,14,15,16,17,18]])
print(arr3)
print(arr1 + arr3)# 兩個結構不相同的數組不能做運算
[[ 1  2  3  4  5  6  7  8  9]
 [10 11 12 13 14 15 16 17 18]]



---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-117-3d8b63f7505e> in <module>
      2 arr3 = np.array([[1,2,3,4,5,6,7,8,9], [10,11,12,13,14,15,16,17,18]])
      3 print(arr3)
----> 4 print(arr1 + arr3)# 兩個結構不相同的數組不能做運算


ValueError: operands could not be broadcast together with shapes (2,4) (2,9) 

3.廣播機制:(形狀不同的數組運算)

執行 broadcast 的前提在於,兩個 ndarray 執行的是 element-wise的運算,Broadcast機制的功能是爲了方便不同形狀的ndarray(numpy庫的核心數據結構)進行數學運算。

當操作兩個數組時,numpy會逐個比較它們的shape(構成的元組tuple),只有在下述情況下,兩個數組才能夠進行數組與數組的運算。

  • 維度相等
  • shape(其中相對應的一個地方爲1)

例如:


Image (3d array):  256 x 256 x 3
Scale (1d array):              3
Result (3d array): 256 x 256 x 3

A      (4d array):  9 x 1 x 7 x 1
B      (3d array):      8 x 1 x 5
Result (4d array):  9 x 8 x 7 x 5

A      (2d array):  5 x 4
B      (1d array):      1
Result (2d array):  5 x 4

A      (3d array):  15 x 3 x 5
B      (3d array):  15 x 1 x 1
Result (3d array):  15 x 3 x 5

如果是下面這樣的,則不匹配:

A  (1d array): 10
B  (1d array): 12
A  (2d array):      2 x 1
B  (3d array):  8 x 4 x 3

4.矩陣運算:

4.1 什麼是矩陣:

矩陣,英文matrix,和array的區別矩陣必須是2維的,但是array可以是多維的。

  • np.mat()
    • 將數組轉換成矩陣類型
import numpy as np
a = np.array([[80, 86],
[82, 80],
[85, 78],
[90, 90],
[86, 82],
[82, 90],
[78, 80],
[92, 94]])
b = np.array([[0.7], [0.3]])
print(a.dtype)

np.mat(a)
int64





matrix([[80, 86],
        [82, 80],
        [85, 78],
        [90, 90],
        [86, 82],
        [82, 90],
        [78, 80],
        [92, 94]])
aa = np.array([
    [
        [1,2,3],[4,5,6]
    ],
    [
        [3,4,6],[8,6,5]
    ]
    
    ])
print(aa)
np.mat(aa)
[[[1 2 3]
  [4 5 6]]

 [[3 4 6]
  [8 6 5]]]



---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-120-a5021d130657> in <module>
      9     ])
     10 print(aa)
---> 11 np.mat(aa)


~/miniconda3/envs/jupyter/lib/python3.6/site-packages/numpy/matrixlib/defmatrix.py in asmatrix(data, dtype)
     69 
     70     """
---> 71     return matrix(data, dtype=dtype, copy=False)
     72 
     73 


~/miniconda3/envs/jupyter/lib/python3.6/site-packages/numpy/matrixlib/defmatrix.py in __new__(subtype, data, dtype, copy)
    135             else:
    136                 intype = N.dtype(dtype)
--> 137             new = data.view(subtype)
    138             if intype != data.dtype:
    139                 return new.astype(intype)


~/miniconda3/envs/jupyter/lib/python3.6/site-packages/numpy/matrixlib/defmatrix.py in __array_finalize__(self, obj)
    180                 return
    181             elif (ndim > 2):
--> 182                 raise ValueError("shape too large to be a matrix.")
    183         else:
    184             newshape = self.shape


ValueError: shape too large to be a matrix.

4.2 矩陣乘法運算:

矩陣乘法的兩個關鍵:

  • 形狀改變;
  • 運算規則;

形狀改變:

(M行,N列)x(N行,L列)=(M行,L列)

必須符合上面的式子,否則運算出錯

運算規則:
在這裏插入圖片描述
矩陣乘法api:

  • np.matmul: (矩陣的叉乘)禁止矩陣與標量的乘法
  • np.dot:點乘
a = np.array([[80, 86],
[82, 80],
[85, 78],
[90, 90],
[86, 82],
[82, 90],
[78, 80],
[92, 94]])

b = np.array([[0.7], [0.3]])

np.matmul(a,b)
array([[81.8],
       [81.4],
       [82.9],
       [90. ],
       [84.8],
       [84.4],
       [78.6],
       [92.6]])
np.dot(a,b)
array([[81.8],
       [81.4],
       [82.9],
       [90. ],
       [84.8],
       [84.4],
       [78.6],
       [92.6]])

六、數組的合併與分割:

1. 數組的合併:

  • numpy.concatenate((a1, a2, …), axis=0): 合併,按行或按列
  • numpy.hstack(tup) Stack arrays in sequence horizontally (column wise).:橫向堆砌
  • numpy.vstack(tup) Stack arrays in sequence vertically (row wise).: 縱向堆砌

示例:

np.concatenate()
import numpy as np
a = np.array([[1,2],[4,5]])

b = np.array([[5,6],[7,8]])
np.concatenate((a,b))# 參數必須以元組的方式傳遞,默認axis=0, 按列合併
array([[1, 2],
       [4, 5],
       [5, 6],
       [7, 8]])
np.concatenate((a,b), axis=1)#
array([[1, 2, 5, 6],
       [4, 5, 7, 8]])
b.T
array([[5],
       [6]])
np.concatenate((a,b.T), axis=1)
array([[1, 2, 5],
       [4, 5, 6]])

2.數組的分割:

  • numpy.split(ary, indices_or_sections, axis=0) Split an array into multiple sub-arrays.
import numpy as np
x = np.arange(9.0)
print(x)
print(np.split(x,3))
[0. 1. 2. 3. 4. 5. 6. 7. 8.]
[array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7., 8.])]
np.split(x,[1,2,3,5])
[array([0.]),
 array([1.]),
 array([2.]),
 array([3., 4.]),
 array([5., 6., 7., 8.])]
np.split(x,[1,4])# 指定切分的位置
[array([0.]), array([1., 2., 3.]), array([4., 5., 6., 7., 8.])]

七、IO操作與數據處理:

1.Numpy讀取

  • genfromtxt(fname[, dtype, comments, …]) Load data from a text file, with missing values handled as specified.
import numpy as np
data = np.genfromtxt("./test.csv", delimiter=",")
data
array([[  nan,   nan,   nan,   nan],
       [  1. , 123. ,   1.4,  23. ],
       [  2. , 110. ,   nan,  18. ],
       [  3. ,   nan,   2.1,  19. ],
       [  5. ,   nan,   nan,   nan]])

2. 如何處理缺失值:

2.1 什麼是缺失值:

什麼時候numpy中會出現nan:當我們讀取本地的文件爲float的時候,如果有缺失(或者爲None),就會出現nan

2.2 缺失值處理:

那麼,在一組數據中單純的把nan替換爲0,合適麼?會帶來什麼樣的影響?

比如,全部替換爲0後,替換之前的平均值如果大於0,替換之後的均值肯定會變小,所以更一般的方式是把缺失的數值替換爲均值(中值)或者是直接刪除有缺失值的一行

所以:

  • 如何計算一組數據的中值或者是均值
  • 如何刪除有缺失數據的那一行(列)在pandas中介紹

八、總結:

在這裏插入圖片描述

相關代碼及文檔下載: https://download.csdn.net/download/qq_35709559/12074449

發佈了101 篇原創文章 · 獲贊 58 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章