Python數據分析系列
Day_02 初識numpy
特點
- 內存佔用小
- 執行速度快
- 可以在整個數組上執行復雜的計算
導包 import numpy as np
numpy的核心對象: np.ndarray多維數組對象
- 長度不可變, 元素可變 (跟c的數組相同)
- 所有元素類型相同 (跟c的數組相同)
- 維度稱之爲軸
- 支持索引與切片 (支持多維索引與切片)
np.ndarray對象常用屬性與方法
屬性/方法 | 功能 | 原型 |
---|---|---|
ndim | 軸個數 (維度) | ndim -> int |
shape | 形狀 (每一維的元素數) | shape -> tuple |
size | 元素數 | size -> int |
dtype | 元素類型 (如: np.int32) | dtype -> dtype |
itemsize | 元素所佔字節數 (元素大小) | itemsize -> int |
T | 轉置 (行變列, 列變行) | 同 transpose() -> ndarray |
reshape() | 塑形 (重整維度) | reshape(*shape, order=‘C’ ) -> ndarray |
flatten() | 展開 (轉爲一軸) | flatten(order=‘C’) -> ndarray |
astype(dtype) | 修改元素類型 | astype(dtype, …) -> ndarray |
numpy對象常用方法
函數 | 功能 | 原型 |
---|---|---|
array() | 從可迭代對象創建多維數組對象 | array(iterable, dtype=None, …) -> ndarray |
arange() | 生成多維數組對象, 類似python的range (一維, 可通過reshape方法塑形) | arange([start,] stop[, step,], dtype=None) -> ndarray |
linspace | 創建線性等分向量 (start-stop區間等分num份) | linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) -> ndarray |
zeros() | 創建一個元素全爲0的多維數組對象 | zeros(shape, dtype=float, order=‘C’) -> ndarray |
ones() | 創建一個元素全爲1的多維數組對象 | ones(shape, dtype=None, order=‘C’) -> ndarray |
empty() | 創建一個未初始化的多維數組對象 | empty(shape, dtype=float, order=‘C’) -> ndarray |
*_like() | *表示zeros或ones或empty, 以另一個多維數組對象爲形狀 | *_like(a, dtype=None, order=‘K’, subok=True) -> ndarray |
eye() | 創建一個對角線爲1的矩陣, 其餘元素填充0 (一般用於one-hot編碼 如: 決策樹算法) | eye(N, M=None, k=0, dtype=float) -> |
運算
算術和比較操作ndarray被定義爲逐元素操作, 並且通常將ndarray對象作爲結果返回
維度相同:
- 長度相同: 兩個數組同位置元素進行計算
- 長度不同: 無法計算
維度不相同:
- 行數相同: 跟每一行進行計算
- 列數相同: 跟每一列進行計算
- 都不同: 無法計算
示例
a = np.array([1, 2, 3]) # 創建一個一軸的多維數組對象
a = np.array([[1, 2, 3], [4, 5, 6]]) # 創建一個兩軸的多維數組對象 (2行3列)
a = np.arange(10) # 創建一個包含元素0-9的一軸的多維數組對象
a = np.arange(10).reshape((2, 5)) # 塑形爲兩軸的多維數組對象 (2行5列)
a = np.zeros(10) # 創建一個元素全爲0的一軸的多維數組對象 (10個元素)
a = np.zeros((2, 5)) # 創建一個元素全爲0的兩軸的多維數組對象 (10個元素)
a = np.zeros_like(a) # 以a爲形狀, 創建一個元素全爲0的多維數組對象 (元素數與a相同)
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = a * b # 兩個多維數組每個元素相乘, 返回新的多維數組對象
c = a * 10 # a中的每個元素與10相乘, 返回新的多維數組對象
a = np.arange(27).reshape((3,3,3)) # 定義三維數組
"""
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
"""
# 切出0, 3, 6, 9, 12, ...
a[:, :, 0].flatten()
"""
array([ 0, 3, 6, 9, 12, 15, 18, 21, 24])
"""