Python numpy詳解


一、Numpy介紹

  • 一個強大的N維數組對象
  • 支持大量的數據運算
  • 集成C / C++和Fortran代碼的工具
  • 眾多機器學習框架的基礎庫(Scipy/Pandas/scikit-learn/Tensorflow)

numpy在存儲數據的時候,數據與數據的地址都是連續的,這樣就給我們操作帶來了好處,處理速度快。在計算機內存里是存儲在一個連續空間上的,而對於這個連續空間,我們如果創建 Array 的方式不同,在這個連續空間上的排列順序也有不同。

  • 創建array的默認方式是 “C-type” 以 row 為主在內存中排列

  • 如果是 “Fortran” 的方式創建的,就是以 column 為主在內存中排列

二、numpy屬性

1、ndarray   N維數組類型

  數組屬性

屬性名字 屬性解釋
ndarray.shape 數組維度的元組
ndarray.flags 有關陣列內存布局的信息
ndarray.ndim 數組維數
ndarray.size 數組中的元素數量
ndarray.itemsize 一個數組元素的長度(字節)
ndarray.nbytes 數組元素消耗的總字節數

  數組類型,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'
# 創建一個數組
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]],[[1,2,3],[4,5,6]]])

# 類型,大小,字節數
a.dtype            # dtype('int64')
a.size               # 元素的個數 6
a.nbytes           # 總字節數 48
a.itemsize         # 一個元素的長度            

# 形狀比較
# 1維形狀 (4,)
# 2維形狀 (2,3)
# 3維形狀 (2, 2, 3)
a.shape                  # (2, 3)
b.shape                   #( 4,)
c.shape                 # (2, 2, 3)

aa = np.array([[1,2,3],[4,5,6]], dtype=np.float32)
aa.dtype         # dtype('float32')



# 創建數組的時候指定類型
arr = np.array(['python','tensorflow','scikit-learn','numpy'],dtype = np.string_)
arr.dtype      #array([b'python', b'tensorflow', b'scikit-learn', b'numpy'], dtype='|S12')

2、數據基本操作

2.1 創建0和1的數組

zero = np.zeros([3, 4])
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])

ones = np.ones([3,4])
array([[1,1, 1, 1]
         [1,1, 1, 1]
         [1,1, 1, 1]])

2.2 利用已有數組創建

# 源碼
def asarray(a, dtype=None, order=None):
    return array(a, dtype, copy=False, order=order)

a = np.array([[1,2,3],[4,5,6]])
# 從現有的數組當中創建,默認設置copy=True
a1 = np.array(a)
# 相當於索引的形式,並沒有真正的創建一個新的,默認設置copy=False
a2 = np.asarray(a)
# np.asanyarray 會返回 ndarray 或者ndarray的子類,而np.asarray 只返回 ndarray.
a3 = np.asanyarray(a)

2.3創建固定范圍的數組

# np.linspace (start, stop, num, endpoint, retstep, dtype)   生成等間隔的序列
# start 序列的起始值
# stop 序列的終止值,
# 如果endpoint為true,該值包含於序列中
# num 要生成的等間隔樣例數量,默認為50
# endpoint 序列中是否包含stop值,默認為ture
# retstep 如果為true,返回樣例,以及連續數字之間的步長
# dtype 輸出ndarray的數據類型

# 生成等間隔的數組
np.linspace(0, 100, 10)

#一個參數 默認起點0,步長為1 輸出:[0 1 2]
a = np.arange(3)

#兩個參數 默認步長為1 輸出[3 4 5 6 7 8]
a = np.arange(3,9)

#三個參數 起點為0,終點為4,步長為0.1
a = np.arange(0, 3, 0.1)

2.4創建隨機數組

# 創建均勻分布的數組
# 0~1
print(np.random.rand(10))       # [0.1316822  0.14809709 0.1721296  0.31960958 0.45602859 0.23868581
 0.3029913  0.13963264 0.34909405 0.16349485]

# 默認范圍一個數
print(np.random.uniform(0, 100))      # 79.1599055190787

# 隨機整數
print(np.random.randint(10))     # 6

# 正態分布
print(np.random.normal(0,1, (5, 10)))

2.5數據操作

arr = np.random.normal(0,1, (5, 10))
arr.shape   # (5, 10)
# 獲取第一個數據的前5個數據
arr[0, 0:5]     # [-0.16934799  1.42139779 -0.42300578  0.87905768 -0.09310058]

# 通過索引獲取數據
arr[0, 0, 1]

# 修改形狀 
reshape:有返回值,所謂有返回值,即不對原始多維數組進行修改;
resize:無返回值,所謂無返回值,即會對原始多維數組進行修改;
# 讓arr的行與arr列反過來
# 在轉換形狀的時候,一定要注意數組的元素匹配
arr.reshape([10, 5])   # 返回新數組
arr.resize([10,5])      # 修改原數組


# 修改類型
# ndarray.astype(type)
arr.reshape([10, 5]).astype(np.int32)

# 修改小數位數
# ndarray.round(arr, out) Return a with each element rounded to the given number of decimals.
np.round(arr[:2, :5], 4)

# 數組轉換
arr.shape     # (5,10)
arr.T.shape    # (10,5)

# 將arr轉換成bytes
arr.tostring()   

3、邏輯運算

# 邏輯判斷
temp > 0.5

# 賦值
temp[temp > 0.5] = 1

3.1通用函數

# np.all()
#判斷[0:2,0:5]是否全是大於0的
np.all(arr[0:2,0:5] > 0)     #返回False/True

# np.unique()
# 返回新的數組的數值,不存在重復的值

#將序列中數值值唯一且不重復的值組成新的序列
change_int = arr[0:2,0:5].astype(int)
np.unique(change_int)

3.2 np.where(三元運算符)

# 通過使用np.where能夠進行更加復雜的運算

np.where()
np.where(temp > 0, 1, 0)    # 把t中小於0的替換成0,其他的替換成1.

# 復合邏輯需要結合np.logical_and和np.logical_or使用
# 判斷大於0.5並且小於1的,換為1,否則為0
np.where(np.logical_and(temp > 0.5, temp < 1), 1, 0)
# 判斷 大於0.5或者小於-0.5的,換為1,否則為0
np.where(np.logical_or(temp > 0.5, temp < -0.5), 1, 0)

4、統計運算

  • 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代表行去進行統計

np.max(arr, axis=1)
np.min(arr, axis=1)
np.std(arr, axis=1)
np.mean(arr, axis=1)

# 獲取變化最大
np.argmax(arr, axis=1)
np.argmax(arr, axis=0)

5、數據間運算

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

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

例如

arr1 = np.array([[1,2,3,2,1,4], [5,6,1,2,3,1]])
arr2 = np.array([[1], [3]])

6、矩陣運算

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

np.mat()

  • 將數組轉換成矩陣類型

6.1 矩陣乘法運算

 

在進行矩陣運算的時候,可以直接使用一個乘法運算API

  • mp.matmul
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]])

ab = np.matmul(a, b)
print(ab)

7、合並、分割

合並:

  • 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).
arr = np.random.normal(0,1,(6,10))
arr1 = arr[:2,:5]
arr2 = arr[2:4,:5]

# axis=0時候,按照數組的行方向拼接在一起  相當於vstack
arr12 = np.concatenate([arr1, arr2], axis=0)
print(arr12)
# axis=1時候,按照數組的列方向拼接在一起  相當於hstack
arr21 = np.concatenate([arr1, arr2], axis=1)
print(arr21)

# np.hstack([arr1, arr2])
# np.vstack([arr1, arr2])

分割:

  • numpy.split(ary, indices_or_sections, axis=0) Split an array into multiple sub-arrays.
arr = np.random.normal(0,1,(6,10))
arr1 = arr[:2,:5]
arr2 = arr[2:4,:5]

# axis=0時候,按照數組的行方向拼接在一起  相當於vstack
arr12 = np.concatenate([arr1, arr2], axis=0)
print(arr12)
# arr12 = [[ 2.36101473  0.59607656  0.05558251  1.76005188 -1.09546167]
 [-0.0909139  -2.4578533   0.03143425 -0.92920756 -0.75200382]
 [-0.78871339 -0.16194897 -0.6846899   0.26065397 -0.46875865]
 [ 0.58308561  0.3746763   0.71939439 -0.08448596 -1.78409148]]

aa = np.split(arr12,4,axis=0)  # 分割成四個數組,按行切割

aa = np.split(arr12,5,axis=0)  # 分割成五個數組,按列切割

8、IO操作與數據處理

Numpy讀取

  • genfromtxt(fname[, dtype, comments, ...])   Load data from a text file, with missing values handled as specified.

測試數據,test.csv文件內容

 

import numpy as np

test = np.genfromtxt("test.csv", delimiter=',')

test  # 當我們讀取本地的文件為float的時候,如果有缺失(或者為None),就會出現nan

# 結果array([[  nan,   nan,   nan,   nan],

       [  1. , 123. ,   1.4,  23. ],

       [  2. , 110. ,   nan,  18. ],

       [  3. ,   nan,   2.1,  19. ]])

test.shape   # (4,4)
type(np.nan)    # float
# numpy不適合數據處理,pandas工具比較合適

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM