簡約而不簡單!值得收藏的 NumPy 小抄表(含主要語法、代碼)

2021-01-18 深度學習這件小事

Numpy是一個用python實現的科學計算的擴展程序庫,包括:3、用於整合C/C++和Fortran代碼的工具包;4、實用的線性代數、傅立葉變換和隨機數生成函數。numpy和稀疏矩陣運算包scipy配合使用更加方便。NumPy(Numeric Python)提供了許多高級的數值編程工具,如:矩陣數據類型、矢量處理,以及精密的運算庫。專為進行嚴格的數字處理而產生。多為很多大型金融公司使用,以及核心的科學計算組織如:Lawrence Livermore,NASA用其處理一些本來使用C++,Fortran或Matlab等所做的任務。本文整理了一個Numpy的小抄表,總結了Numpy的常用操作,可以收藏慢慢看。


   安裝Numpy


可以通過 Pip 或者 Anaconda安裝Numpy:


   本文目錄


   基礎

NumPy最常用的功能之一就是NumPy數組:列表和NumPy數組的最主要區別在於功能性和速度。


列表提供基本操作,但NumPy添加了FTTs、卷積、快速搜索、基本統計、線性代數、直方圖等。


兩者數據科學最重要的區別是能夠用NumPy數組進行元素級計算。

axis 0 通常指行

axis 1 通常指列


操作描述文檔np.array([1,2,3])一維數組https://numpy.org/doc/stable/reference/generated/numpy.array.html#numpy.arraynp.array([(1,2,3),(4,5,6)])二維數組https://numpy.org/doc/stable/reference/generated/numpy.array.html#numpy.arraynp.arange(start,stop,step)等差數組https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html


佔位符


操作

描述

文檔

np.linspace(0,2,9)

數組中添加等差的值

https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html

np.zeros((1,2))

創建全0數組

docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

np.ones((1,2))

創建全1數組

https://docs.scipy.org/doc/numpy/reference/generated/numpy.ones.html#numpy.ones

np.random.random((5,5))

創建隨機數的數組

https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.random.html

np.empty((2,2))

創建空數組

https://numpy.org/doc/stable/reference/generated/numpy.empty.html


舉例:

import numpy as np
# 1 dimensionalx = np.array([1,2,3])# 2 dimensionaly = np.array([(1,2,3),(4,5,6)])
x = np.arange(3)>>> array([0, 1, 2])
y = np.arange(3.0)>>> array([ 0., 1., 2.])
x = np.arange(3,7)>>> array([3, 4, 5, 6])
y = np.arange(3,7,2)>>> array([3, 5])


   數組
數組屬性


語法描述文檔array.shape維度(行,列)https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.htmllen(array)數組長度https://docs.python.org/3.5/library/functions.html#lenarray.ndim數組的維度數https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.ndim.htmlarray.size數組的元素數https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.size.htmlarray.dtype數據類型https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.htmlarray.astype(type)轉換數組類型https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.htmltype(array)顯示數組類型https://numpy.org/doc/stable/user/basics.types.html


拷貝 /排序


操作描述文檔np.copy(array)創建數組拷貝https://docs.scipy.org/doc/numpy/reference/generated/numpy.copy.htmlother = array.copy()創建數組深拷貝https://docs.scipy.org/doc/numpy/reference/generated/numpy.copy.htmlarray.sort()排序一個數組https://docs.scipy.org/doc/numpy/reference/generated/numpy.sort.htmlarray.sort(axis=0)按照指定軸排序一個數組https://docs.scipy.org/doc/numpy/reference/generated/numpy.sort.html舉例

import numpy as np# Sort sorts in ascending ordery = np.array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])y.sort()print(y)>>> [ 1 2 3 4 5 6 7 8 9 10]

數組操作例程增加或減少元素操作描述文檔np.append(a,b)增加數據項到數組https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.htmlnp.insert(array, 1, 2, axis)沿著數組0軸或者1軸插入數據項https://docs.scipy.org/doc/numpy/reference/generated/numpy.insert.htmlnp.resize((2,4))將數組調整為形狀(2,4)https://docs.scipy.org/doc/numpy/reference/generated/numpy.resize.htmlnp.delete(array,1,axis)從數組裡刪除數據項https://numpy.org/doc/stable/reference/generated/numpy.delete.html

舉例

import numpy as np# Append items to arraya = np.array([(1, 2, 3),(4, 5, 6)])b = np.append(a, [(7, 8, 9)])print(b)>>> [1 2 3 4 5 6 7 8 9]
# Remove index 2 from previous arrayprint(np.delete(b, 2))>>> [1 2 4 5 6 7 8 9]

組合數組操作描述文檔np.concatenate((a,b),axis=0)連接2個數組,添加到末尾https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.htmlnp.vstack((a,b))按照行堆疊數組https://numpy.org/doc/stable/reference/generated/numpy.vstack.htmlnp.hstack((a,b))按照列堆疊數組docs.scipy.org/doc/numpy/reference/generated/numpy.hstack.html#numpy.hstack舉例

import numpy as npa = np.array([1, 3, 5])b = np.array([2, 4, 6])
# Stack two arrays row-wiseprint(np.vstack((a,b)))>>> [[1 3 5] [2 4 6]]
# Stack two arrays column-wiseprint(np.hstack((a,b)))>>> [1 3 5 2 4 6]

分割數組


操作

描述

文檔

numpy.split()

分割數組

https://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html

np.array_split(array, 3)

將數組拆分為大小(幾乎)相同的子數組

https://docs.scipy.org/doc/numpy/reference/generated/numpy.array_split.html#numpy.array_split

numpy.hsplit(array, 3)

在第3個索引處水平拆分數組

https://numpy.org/doc/stable/reference/generated/numpy.hsplit.html#numpy.hsplit

舉例

# Split array into groups of ~3a = np.array([1, 2, 3, 4, 5, 6, 7, 8])print(np.array_split(a, 3))>>> [array([1, 2, 3]), array([4, 5, 6]), array([7, 8])]

數組形狀變化操作描述文檔other = ndarray.flatten()平鋪一個二維數組到一維數組https://numpy.org/doc/stable/reference/generated/numpy.ndarray.flatten.htmlnumpy.flip()翻轉一維數組中元素的順序https://docs.scipy.org/doc/stable/reference/generated/numpy.flip.htmlnp.ndarray[::-1]翻轉一維數組中元素的順序
reshape改變數組的維數https://docs.scipy.org/doc/stable/reference/generated/numpy.reshape.htmlsqueeze從數組的形狀中刪除單維度條目https://numpy.org/doc/stable/reference/generated/numpy.squeeze.htmlexpand_dims擴展數組維度
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.expand_dims.html其他操作描述文檔other = ndarray.flatten()平鋪2維數組到1維數組https://numpy.org/doc/stable/reference/generated/numpy.ndarray.flatten.htmlarray = np.transpose(other)
array.T數組轉置https://numpy.org/doc/stable/reference/generated/numpy.transpose.htmlinverse = np.linalg.inv(matrix)求矩陣的逆矩陣https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.inv.html


舉例

# Find inverse of a given matrix>>> np.linalg.inv([[3,1],[2,4]])array([[ 0.4, -0.1], [-0.2, 0.3]])

   數學計算操作操作描述文檔np.add(x,y)
x + y加https://docs.scipy.org/doc/numpy/reference/generated/numpy.add.htmlnp.substract(x,y)
x - y減https://docs.scipy.org/doc/numpy/reference/generated/numpy.subtract.html#numpy.subtractnp.divide(x,y)
x / y除https://docs.scipy.org/doc/numpy/reference/generated/numpy.divide.html#numpy.dividenp.multiply(x,y)
x * y乘https://docs.scipy.org/doc/numpy/reference/generated/numpy.multiply.html#numpy.multiplynp.sqrt(x)平方根https://docs.scipy.org/doc/numpy/reference/generated/numpy.sqrt.html#numpy.sqrtnp.sin(x)元素正弦https://docs.scipy.org/doc/numpy/reference/generated/numpy.sin.html#numpy.sinnp.cos(x)元素餘弦https://docs.scipy.org/doc/numpy/reference/generated/numpy.cos.html#numpy.cosnp.log(x)元素自然對數https://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html#numpy.lognp.dot(x,y)點積https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.htmlnp.roots([1,0,-4])給定多項式係數的根https://docs.scipy.org/doc/numpy/reference/generated/numpy.roots.html


# If a 1d array is added to a 2d array (or the other way), NumPy# chooses the array with smaller dimension and adds it to the one# with bigger dimensiona = np.array([1, 2, 3])b = np.array([(1, 2, 3), (4, 5, 6)])print(np.add(a, b))>>> [[2 4 6] [5 7 9]]
# Example of np.roots# Consider a polynomial function (x-1)^2 = x^2 - 2*x + 1# Whose roots are 1,1>>> np.roots([1,-2,1])array([1., 1.])# Similarly x^2 - 4 = 0 has roots as x=±2>>> np.roots([1,0,-4])array([-2., 2.])

比較操作描述文檔==等於https://docs.python.org/2/library/stdtypes.html!=不等於
https://docs.python.org/2/library/stdtypes.html<小於https://docs.python.org/2/library/stdtypes.html>大於https://docs.python.org/2/library/stdtypes.html<=小於等於https://docs.python.org/2/library/stdtypes.html>=大於等於https://docs.python.org/2/library/stdtypes.htmlnp.array_equal(x,y)數組比較https://numpy.org/doc/stable/reference/generated/numpy.array_equal.html舉例:

# Using comparison operators will create boolean NumPy arraysz = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])c = z < 6print(c)>>> [ True True True True True False False False False False]

基本的統計操作描述文檔np.mean(array)Meanhttps://numpy.org/doc/stable/reference/generated/numpy.mean.html#numpy.meannp.median(array)Medianhttps://numpy.org/doc/stable/reference/generated/numpy.median.html#numpy.medianarray.corrcoef()Correlation Coefficienthttps://numpy.org/doc/stable/reference/generated/numpy.corrcoef.html#numpy.corrcoefnp.std(array)Standard Deviationhttps://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html#numpy.std


舉例

# Statistics of an arraya = np.array([1, 1, 2, 5, 8, 10, 11, 12])
# Standard deviationprint(np.std(a))>>> 4.2938910093294167
# Medianprint(np.median(a))>>> 6.5

更多操作描述文檔array.sum()數組求和https://numpy.org/doc/stable/reference/generated/numpy.sum.htmlarray.min()數組求最小值https://numpy.org/doc/stable/reference/generated/numpy.ndarray.min.htmlarray.max(axis=0)數組求最大值(沿著0軸)
array.cumsum(axis=0)指定軸求累計和https://numpy.org/doc/stable/reference/generated/numpy.cumsum.html


   切片和子集


操作描述文檔array[i]索引i處的一維數組https://numpy.org/doc/stable/reference/arrays.indexing.htmlarray[i,j]索引在[i][j]處的二維數組https://numpy.org/doc/stable/reference/arrays.indexing.htmlarray[i<4]布爾索引https://numpy.org/doc/stable/reference/arrays.indexing.htmlarray[0:3]選擇索引為 0, 1和 2https://numpy.org/doc/stable/reference/arrays.indexing.htmlarray[0:2,1]選擇第0,1行,第1列https://numpy.org/doc/stable/reference/arrays.indexing.htmlarray[:1]選擇第0行數據項 (與[0:1, :]相同)https://numpy.org/doc/stable/reference/arrays.indexing.htmlarray[1:2, :]選擇第1行https://numpy.org/doc/stable/reference/arrays.indexing.html[comment]: <> "array[1,...]等同於 array[1,:,:]array[ : :-1]反轉數組同上


舉例

b = np.array([(1, 2, 3), (4, 5, 6)])
# The index *before* the comma refers to *rows*,# the index *after* the comma refers to *columns*print(b[0:1, 2])>>> [3]
print(b[:len(b), 2])>>> [3 6]
print(b[0, :])>>> [1 2 3]
print(b[0, 2:])>>> [3]
print(b[:, 0])>>> [1 4]
c = np.array([(1, 2, 3), (4, 5, 6)])d = c[1:2, 0:2]print(d)>>> [[4 5]]


切片舉例


import numpy as npa1 = np.arange(0, 6)a2 = np.arange(10, 16)a3 = np.arange(20, 26)a4 = np.arange(30, 36)a5 = np.arange(40, 46)a6 = np.arange(50, 56)a = np.vstack((a1, a2, a3, a4, a5, a6))


生成矩陣和切片圖示




   小技巧


例子將會越來越多的,歡迎大家提交。

布爾索引 

# Index trick when working with two np-arraysa = np.array([1,2,3,6,1,4,1])b = np.array([5,6,7,8,3,1,2])
# Only saves a at index where b == 1other_a = a[b == 1]#Saves every spot in a except at index where b != 1other_other_a = a[b != 1]

import numpy as npx = np.array([4,6,8,1,2,6,9])y = x > 5print(x[y])>>> [6 8 6 9]
# Even shorterx = np.array([1, 2, 3, 4, 4, 35, 212, 5, 5, 6])print(x[x < 5])>>> [1 2 3 4 4]


【參考】

https://github.com/juliangaal/python-cheat-sheet

相關焦點

  • 簡約而不簡單|值得收藏的Numpy小抄表(含主要語法、代碼)
    安裝Numpy可以通過 Pip 或者 Anaconda安裝Numpy:或本文目錄基礎NumPy最常用的功能之一就是NumPy數組:列表和NumPy數組的最主要區別在於功能性和速度。x = np.arange(3,7)>>> array([3, 4, 5, 6])y = np.arange(3,7,2)>>> array([3, 5])數組屬性數組屬性語法描述文檔array.shape維度(行,列)https://docs.scipy.org/doc/numpy/
  • 小白學數據小抄放送 Python,R,大數據,機器學習
    Python基礎小抄表 這張由Datacamp製作的小抄表覆蓋了所有Python數據科學需要的基礎知識。如果你剛開始用Python,可以留著這張做快速參考。背下這些小抄的代碼變量、數據類型函數、字符串操作、類型轉換、列表和常用操作。尤其是它列出了重要的Python包,給出了用於選擇並導入包的小抄代碼。
  • 小白學數據28張小抄放送 Python,R,大數據,機器學習
    Python基礎小抄表 這張由Datacamp製作的小抄表覆蓋了所有Python數據科學需要的基礎知識。如果你剛開始用Python,可以留著這張做快速參考。背下這些小抄的代碼變量、數據類型函數、字符串操作、類型轉換、列表和常用操作。尤其是它列出了重要的Python包,給出了用於選擇並導入包的小抄代碼。
  • 詳解:Python 取numpy數組的某幾行某幾列方法(含對與錯示例)
    詳解:Python 取numpy數組的某幾行某幾列方法(含對與錯示例) 今天為大家帶來的內容是Python 取numpy數組的某幾行某幾列方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,要是喜歡的話記得點讚轉發收藏不迷路哦!!!
  • python數據科學系列:numpy入門詳細教程
    本篇先從numpy開始,對numpy常用的方法進行思維導圖式梳理,多數方法僅拉單列表,部分接口輔以解釋說明及代碼案例。最後分享了個人關於axis和廣播機制的理解。本文知識要點一級菜單    另外,當resize新尺寸參數與原數組大小不一致時,要求操作對象具有原數組的,而不能是view或簡單賦值。(具體參考08 視圖與拷貝一節)
  • Python數據分析類庫系列-Numpy之多維數組ndarray
    NumPy可以在整個數組上執行複雜的計算,而不需要Python的for循環。你可以利用這種數組對整塊數據執行一些數學運算,其語法跟標量元素之間的運算一樣。 要明白Python是如何利用與標量值類似的語法進行批次計算,我先引入NumPy,然後生成一個包含隨機數據的小數組: import numpy as np data = np.random.randn(2,3)data out:
  • Numpy入門詳細教程
    本篇先從numpy開始,對numpy常用的方法進行思維導圖式梳理,多數方法僅拉單列表,部分接口輔以解釋說明及代碼案例。最後分享了個人關於axis和廣播機制的理解。數組變形是指對給定數組重新整合各維度大小的過程,numpy封裝了4類基本的變形操作:轉置、展平、尺寸重整和複製。主要方法接口如下:
  • 小升初:英語語法基礎知識匯總,內容全面,值得「收藏」!
    小升初:英語語法基礎知識匯總,內容全面,值得「收藏」!英語作為一門語言類的科目, 跟語文一樣,有很多的共同點,最為明顯的就是需要記背的知識點太多!也因此有很多孩子不喜歡英語,覺得背這些單詞短語實在是太枯燥乏味了,還不如一道數學題來得有趣。
  • Python的武器庫05:numpy模塊(下)
    python的語法並不簡單,有複雜難懂的部分,之所以有這樣一句格言,是因為python中有很多強大的模塊,就像一個武器庫。Python正式由於這些模塊的出現,只要引入這個模塊,調用這個模塊的集成函數,問題迎刃而解;不需要從頭開始,節省了大量的時間。上一篇文章主要講述了numpy的數學函數,這節課主要講一下numpy如何創建矩陣,以及對矩陣的一些運算。
  • 簡約而不簡單,低調中帶有霸氣的百達翡麗鸚鵡螺
    雖然接觸腕錶有幾年的時間,但是對於百達翡麗這個品牌一直處於邊緣試探的狀態,主要是感覺這個品牌還是離我很遙遠,但不知道的是,我與百達翡麗的一場邂逅正在悄悄逼近。
  • 現代簡約裝修風格讓你家簡約不簡單
    川北在線核心提示:原標題:現代簡約裝修風格讓你家簡約不簡單 現代簡約裝修風格是現在較流行的風格之一,流暢的線條和簡約的設計既是這種風格的特點,也是這種風格的優點,既不需要過多的裝飾,也能體現簡潔的時尚品味、健康簡約的生活方式,現代簡約裝修風格可以讓你的家簡約不簡單。
  • NumPy ndarray數組的創建
    NumPy 是 Python 的外部庫,不在標準庫中,若要使用它,需要先導入 NumPy:import numpy as
  • Python編程:如何規範numpy中數組元素的列印輸出格式
    引言對於Python語言開發者,如果你經常處理大量數據運算的話,numpy是一個必不可少的程序擴展庫,它支持大維度數組與矩陣運算,提供了非常豐富的數學運算函數,並且,相對於Python自身提供的列表類型,它在運算速度上有著無與倫比的優勢。
  • python數據分析包|Pandas&NumPy小抄(Cheat_Sheet)
    3、NumPy速查手冊二文本格式#Importing/exporting#numpy讀入及保存內容np.loadtxt('file.txt') | From a text filefile.csv',delimiter=',') | From a CSV filenp.savetxt('file.txt',arr,delimiter=' ') | Writes to a text filenp.savetxt('file.csv',arr,delimiter=',') | Writes to a CSV file#Creating Arrays#numpy
  • 如何將Numpy加速700倍?用 CuPy 呀
    只要用兼容的 CuPy 代碼替換 Numpy 代碼,用戶就可以實現 GPU 加速。CuPy 支持 Numpy 的大多數數組運算,包括索引、廣播、數組數學以及各種矩陣變換。如果遇到一些不支持的特殊情況,用戶也可以編寫自定義 Python 代碼,這些代碼會利用到 CUDA 和 GPU 加速。
  • 第04篇:資料庫中如何使用代碼實現建庫、建表、建約束
    前面在第一篇中,曾主要講解通過資料庫管理系統(DBMS)的圖形化界面實現建庫、建表、建約束。雖然簡單易操作,但如果不小心將資料庫、表格意外刪除,就需要重新創建;如果多次執行這樣的操作就會感覺非常繁瑣。再者當項目測試完成後,需要部署在客戶的真實電腦上。
  • 4個Python初學者必學的Numpy小技巧
    下面小芯就基於實踐整理出了Python初學者應該學習的4個numpy技巧,它們能夠幫助你編寫更簡潔易讀的代碼。在學習numpy技巧之前,請確保已熟悉以下文章中的一些Python內置功能。1. 掩碼數組——選擇數據集是不完善的,它們總是包含缺失或無效記錄的數組,而這些記錄是時常需要忽略的。例如,由於傳感器故障,氣象站的測量值可能包含缺失值。
  • 好程式設計師Python培訓分享numpy簡介
    好程式設計師Python培訓分享numpy簡介:一、numpy簡介:NumPy是一個功能強大的Python庫,主要用於對多維數組執行計算。NumPy這個詞來源於兩個單詞-- Numerical和Python。NumPy提供了大量的庫函數和操作,可以幫助程式設計師輕鬆地進行數值計算。
  • 如何獲取numpy數組的真實地址?如何與ctypes數組共享內存?
    那麼,如何使用ctypes庫定義一個與numpy共享內存空間的數組變量呢?仍以上面的例子,定義一個uint8類型的數組b,與a數組共享內存區域,可使用下面的代碼:b = (c_uint8*len(a)).from_address(a.
  • Python學習第112課——numpy中數組查找元素和改變元素的小技巧
    代碼如下:現在我們學習幾個用index找到ndarray中元素的小技巧。★技巧1:★技巧2:以上兩種寫法運行結果都是:以上兩種簡寫技巧,相當於從h中找到元素時,通過兩個list[0,1,2]和[2,1,0],每個list的元素一一對應,分別取出第1行第3列、第2行第2列、第3行第1列的元素,三個元素分別為3、5、7。