# Python NumPy 實(shí)例教程 [譯]
*在本教程中伦意,您將找到使用NumPy解決數(shù)值計(jì)算和科學(xué)計(jì)算問題的解決方案咒唆。*
NumPy(Numerical Python的縮寫)是一個(gè)用于科學(xué)計(jì)算的開源Python庫。
它提供了創(chuàng)建多維數(shù)組對象和執(zhí)行更快的數(shù)學(xué)運(yùn)算的能力了讨,包含很多常用的數(shù)學(xué)方法捻激,比如傅立葉變換(FT)和隨機(jī)數(shù)發(fā)生器(RNG)之類的線性代數(shù)和復(fù)數(shù)運(yùn)算的方法。
我們在Python數(shù)據(jù)分析中經(jīng)常使用的類庫前计,例如 **scikit-learn**胞谭, **SciPy** 和 **Pandas**都使用了NumPy的一些功能。
------
## 創(chuàng)建NumPy數(shù)組
要創(chuàng)建NumPy數(shù)組男杈,我們需要將方括號內(nèi)的元素值列表作為參數(shù)傳遞給`np.array()`方法丈屹。
三維數(shù)組是二維數(shù)組的矩陣。 也可以將三維數(shù)組稱為列表的嵌套伶棒,其中每個(gè)元素也是元素列表旺垒。
例:
```
import numpy as np
array1d = np.array([1, 2, 3, 4, 5, 6])
array2d = np.array([[1, 2, 3], [4, 5, 6]])
array3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(array1d)
print("-" * 10)
print(array2d)
print("-" * 10)
print(array3d)
```
輸出:
```
[1 2 3 4 5 6]
----------
[[1 2 3]
[4 5 6]]
----------
[[[ 1? 2? 3]
? [ 4? 5? 6]]
[[ 7? 8? 9]
? [10 11 12]]]
```
NumPy中多維數(shù)組的主要數(shù)據(jù)結(jié)構(gòu)是**ndarray**類。其基本屬性如下所示:
| 屬性? | 描述? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? |
| ------ | -------------------------------------- |
| Shape? | 一個(gè)元組肤无,表示數(shù)組每個(gè)維度的元素?cái)?shù)量先蒋。 |
| Size? | 數(shù)組中的元素總數(shù)。? ? ? ? ? ? ? ? ? ? |
| Ndim? | 數(shù)組的維數(shù)宛渐。? ? ? ? ? ? ? ? ? ? ? ? ? |
| nbytes | 用于存儲數(shù)據(jù)的字節(jié)數(shù)竞漾。? ? ? ? ? ? ? ? |
| dtype? | 存儲在數(shù)組中的元素的數(shù)據(jù)類型。? ? ? ? |
------
### NumPy支持的數(shù)據(jù)類型
`dtype`方法確定存儲在NumPy數(shù)組中的元素的數(shù)據(jù)類型窥翩。您還可以使用`dtype`選項(xiàng)作為創(chuàng)建數(shù)組方法的參數(shù)业岁,顯式定義元素的數(shù)據(jù)類型。
| dtype? ? ? | 變量? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | 描述? ? ? ? ? ? ? ? ? |
| ---------- | ----------------------------------- | --------------------- |
| `int`? ? ? | int8, int16, int32, int64? ? ? ? ? | 整型? ? ? ? ? ? ? ? ? |
| `uint`? ? | uint8, uint16, uint32, uint64? ? ? | 無符號(非負(fù))整數(shù)? ? |
| `bool`? ? | Bool? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | 布爾值 (True或 False) |
| code>float | float16, float32, float64, float128 | 浮點(diǎn)數(shù)? ? ? ? ? ? ? ? |
| `complex`? | complex64, complex128, complex256? | 復(fù)數(shù)? ? ? ? ? ? ? ? ? |
例:
```
import numpy as np
type1 = np.array([1, 2, 3, 4, 5, 6])
type2 = np.array([1.5, 2.5, 0.5, 6])
type3 = np.array(['a', 'b', 'c'])
type4 = np.array(["Canada", "Australia"], dtype='U5')
type5 = np.array([555, 666], dtype=float)
print(type1.dtype)
print(type2.dtype)
print(type3.dtype)
print(type4.dtype)
print(type5.dtype)
print(type4)
```
輸出:
```
int32
float64
<U1
<U5
float64
['Canad' 'Austr']
```
------
### 數(shù)組的大小
`shape`方法以(m寇蚊,n)的形式確定NumPy數(shù)組的大小笔时,即(行數(shù))x(列數(shù))。
例:
```
import numpy as np
array1d = np.array([1, 2, 3, 4, 5, 6])
array2d = np.array([[1, 2, 3], [4, 5, 6]])
array3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(array1d.shape)
print(array2d.shape)
print(array3d.shape)
```
輸出:
```
(6,)
(2, 3)
(2, 2, 3)
```
------
### 數(shù)組的維度
`ndim`方法確定NumPy數(shù)組的維數(shù)仗岸。
例:
```
import numpy as np
array1d = np.array([1, 2, 3, 4, 5, 6])
print(array1d.ndim)? # 1
array2d = np.array([[1, 2, 3], [4, 5, 6]])
print(array2d.ndim)? # 2
array3d = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
array3d = array3d.reshape(2, 3, 2)
print(array3d.ndim)? # 3
```
------
### 修改數(shù)組維度
`resize()`方法修改現(xiàn)有的維度大小和數(shù)組本身允耿。
例:
```
import numpy as np
thearray = np.array([1, 2, 3, 4, 5, 6, 7, 8])
thearray.resize(4)
print(thearray)
print("-" * 10)
thearray = np.array([1, 2, 3, 4, 5, 6, 7, 8])
thearray.resize(2, 4)
print(thearray)
print("-" * 10)
thearray = np.array([1, 2, 3, 4, 5, 6, 7, 8])
thearray.resize(3, 3)
print(thearray)
```
輸出:
```
[1 2 3 4]
----------
[[1 2 3 4]
[5 6 7 8]]
----------
[[1 2 3]
[4 5 6]
[7 8 0]]
```
------
### 修改數(shù)組維度
`reshape()`方法修改數(shù)組現(xiàn)有維度大小,但原始數(shù)組保持不變扒怖。
例:
```
import numpy as np
thearray = np.array([1, 2, 3, 4, 5, 6, 7, 8])
thearray = thearray.reshape(2, 4)
print(thearray)
print("-" * 10)
thearray = thearray.reshape(4, 2)
print(thearray)
print("-" * 10)
thearray = thearray.reshape(8, 1)
print(thearray)
```
輸出:
```
[[1 2 3 4]
[5 6 7 8]]
----------
[[1 2]
[3 4]
[5 6]
[7 8]]
----------
[[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]]
```
------
### 將List或Tuple轉(zhuǎn)換為NumPy數(shù)組
`array()`函數(shù)也可以接受列表右犹,元組和其他**numpy.ndarray** 對象來創(chuàng)建新的數(shù)組對象。
例:
```
import numpy as np
thelist = [1, 2, 3]
print(type(thelist))? # <class 'list'>
array1 = np.array(thelist)
print(type(array1))? # <class 'numpy.ndarray'>
thetuple = ((1, 2, 3))
print(type(thetuple))? # <class 'tuple'>
array2 = np.array(thetuple)
print(type(array2))? # <class 'numpy.ndarray'>
array3 = np.array([thetuple, thelist, array1])
print(array3)
```
輸出:
```
<class 'list'>
<class 'numpy.ndarray'>
<class 'tuple'>
<class 'numpy.ndarray'>
[[1 2 3]
[1 2 3]
[1 2 3]]
```
------
## 用于創(chuàng)建數(shù)組的特殊NumPy函數(shù)
### arange()
`arange()`函數(shù)創(chuàng)建一個(gè)在指定開始值姚垃,結(jié)束值和增量值的具有均勻間隔的數(shù)組。
一般形式: `np.arange(起始值,結(jié)束值,增量)`
例:
`reshape` 函數(shù)用于更改其維度:
```
import numpy as np
array1d = np.arange(5)? # 1 row and 5 columns
print(array1d)
array1d = np.arange(0, 12, 2)? # 1 row and 6 columns
print(array1d)
array2d = np.arange(0, 12, 2).reshape(2, 3)? # 2 rows 3 columns
print(array2d)
array3d = np.arange(9).reshape(3, 3)? # 3 rows and columns
print(array3d)
```
輸出:
```
[0 1 2 3 4]
[ 0? 2? 4? 6? 8 10]
[[ 0? 2? 4]
[ 6? 8 10]]
[[0 1 2]
[3 4 5]
[6 7 8]]
```
------
### linspace()
`linspace()`函數(shù)生成一個(gè)在指定的起始值和結(jié)束值之間指定元素?cái)?shù)量盼忌,具有均勻間隔值的數(shù)組积糯。
一般形式: `np.linspace(起始值,結(jié)束值,元素?cái)?shù))`
例:
```
import numpy as np
array1d = np.linspace(1, 12, 2)
print(array1d)
array1d = np.linspace(1, 12, 4)
print(array1d)
array2d = np.linspace(1, 12, 12).reshape(4, 3)
print(array2d)
```
輸出:
```
[ 1. 12.]
[ 1.? ? ? ? ? 4.66666667? 8.33333333 12.? ? ? ? ]
[[ 1.? 2.? 3.]
[ 4.? 5.? 6.]
[ 7.? 8.? 9.]
[10. 11. 12.]]
```
------
### logspace()
`logspace()`函數(shù)生成一個(gè)在指定的起始值和結(jié)束值之間掂墓,以對數(shù)值間隔的數(shù)組。
例:
```
import numpy as np
thearray = np.logspace(5, 10, num=10, base=10000000.0, dtype=float)
print(thearray)
```
輸出:
```
[1.00000000e+35 7.74263683e+38 5.99484250e+42 4.64158883e+46
3.59381366e+50 2.78255940e+54 2.15443469e+58 1.66810054e+62
1.29154967e+66 1.00000000e+70]
```
------
### 0數(shù)組
The zeros() function, generates an array with the specified dimensions and data type that is filled with **zeros**.
`zeros()`函數(shù)生成一個(gè)具有指定維度和數(shù)據(jù)類型的數(shù)組看成,該數(shù)組內(nèi)容全部填充為**0**君编。
例:
```
import numpy as np
array1d = np.zeros(3)
print(array1d)
array2d = np.zeros((2, 4))
print(array2d)
```
輸出:
```
[0. 0. 0.]
[[0. 0. 0. 0.]
[0. 0. 0. 0.]]
```
------
### 1數(shù)組
`ones()`函數(shù)生成一個(gè)具有指定維度和數(shù)據(jù)類型的數(shù)組,該數(shù)組內(nèi)容全部填充為**1**川慌。
例:
```
import numpy as np
array1d = np.ones(3)
print(array1d)
array2d = np.ones((2, 4))
print(array2d)
```
輸出:
```
[1. 1. 1.]
[[1. 1. 1. 1.]
[1. 1. 1. 1.]]
```
------
### 填充數(shù)組
`full()` 函數(shù)生成一個(gè)具有指定維度和數(shù)據(jù)類型的數(shù)組吃嘿,該數(shù)組內(nèi)容全部填充為**指定值**。
例:
```
import numpy as np
array1d = np.full((3), 2)
print(array1d)
array2d = np.full((2, 4), 3)
print(array2d)
```
輸出:
```
[2 2 2]
[[3 3 3 3]
[3 3 3 3]]
```
------
### Eye數(shù)組
`eye()`函數(shù)返回一個(gè)數(shù)組梦重,除了第k個(gè)對角線上元素值等于1兑燥,其它所有元素值均為0。
例:
```
import numpy as np
array1 = np.eye(3, dtype=int)
print(array1)
array2 = np.eye(5, k=2)
print(array2)
```
輸出:
```
[[1 0 0]
[0 1 0]
[0 0 1]]
[[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]
```
------
###? 隨機(jī)數(shù)數(shù)組
`np.random.rand`方法生成一個(gè)隨機(jī)數(shù)在0和1之間的數(shù)組琴拧。
`np.random.randn`方法生成一個(gè)隨機(jī)數(shù)的數(shù)組降瞳,隨機(jī)數(shù)為0或1。
`np.random.randint`方法生成一個(gè)數(shù)組蚓胸,其隨機(jī)數(shù)均勻分布在0和給定的整數(shù)之間挣饥。
例:
```
import numpy as np
print(np.random.rand(3, 2))? # Uniformly distributed values.
print(np.random.randn(3, 2))? # Normally distributed values.
# Uniformly distributed integers in a given range.
print(np.random.randint(2, size=10))
print(np.random.randint(5, size=(2, 4)))
```
輸出:
```
[[0.68428242 0.62467648]
[0.28595395 0.96066372]
[0.63394485 0.94036659]]
[[0.29458704 0.84015551]
[0.42001253 0.89660667]
[0.50442113 0.46681958]]
[0 1 1 0 0 0 0 1 0 0]
[[3 3 2 3]
[2 1 2 0]]
```
------
### 對角線數(shù)組
`identity()`函數(shù)生成主對角線上元素值為**1**的方形數(shù)組,而`diag()`函數(shù)提取或構(gòu)造對角線數(shù)組沛膳。
例:
```
import numpy as np
print(np.identity(3))
print(np.diag(np.arange(0, 8, 2)))
print(np.diag(np.diag(np.arange(9).reshape((3,3)))))
```
輸出:
```
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
[[0 0 0 0]
[0 2 0 0]
[0 0 4 0]
[0 0 0 6]]
[[0 0 0]
[0 4 0]
[0 0 8]]
```
------
## NumPy數(shù)組的操作
### 索引
NumPy在創(chuàng)建數(shù)組時(shí)創(chuàng)建相應(yīng)的索引扔枫。 為了訪問數(shù)組的單個(gè)或多個(gè)項(xiàng),我們需要在方括號中傳遞索引锹安。
二維數(shù)組中的索引由一對值表示短荐,其中第一個(gè)值是行的索引,第二個(gè)值是列的索引八毯。
例:
```
import numpy as np
array1d = np.array([1, 2, 3, 4, 5, 6])
print(array1d[0])? # Get first value
print(array1d[-1])? # Get last value
print(array1d[3])? # Get 4th value from first
print(array1d[-5])? # Get 5th value from last
# Get multiple values
print(array1d[[0, -1]])
print("-" * 10)
array2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(array2d)
print("-" * 10)
print(array2d[0, 0])? # Get first row first col
print(array2d[0, 1])? # Get first row second col
print(array2d[0, 2])? # Get first row third col
print(array2d[0, 1])? # Get first row second col
print(array2d[1, 1])? # Get second row second col
print(array2d[2, 1])? # Get third row second col
```
輸出:
```
1
6
4
2
[1 6]
----------
[[1 2 3]
[4 5 6]
[7 8 9]]
----------
1
2
3
2
5
8
```
------
### 多維索引
三維數(shù)組中的索引基于語法:`array3d [L, M, N] 搓侄,其中L是第一個(gè)索引,M是行號话速, N是列號讶踪。`
例:
```
import numpy as np
array3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(array3d)
print(array3d[0, 0, 0])
print(array3d[0, 0, 1])
print(array3d[0, 0, 2])
print(array3d[0, 1, 0])
print(array3d[0, 1, 1])
print(array3d[0, 1, 2])
print(array3d[1, 0, 0])
print(array3d[1, 0, 1])
print(array3d[1, 0, 2])
print(array3d[1, 1, 0])
print(array3d[1, 1, 1])
print(array3d[1, 1, 2])
```
輸出:
```
[[[ 1? 2? 3]
? [ 4? 5? 6]]
[[ 7? 8? 9]
? [10 11 12]]]
1
2
3
4
5
6
7
8
9
10
11
12
```
------
###? 一維數(shù)組切片
切片允許提取數(shù)組的部分或選擇現(xiàn)有數(shù)組的子集以生成新數(shù)組。 切片由方括號內(nèi)的冒號(:)分隔數(shù)字序列泊交。
例
```
import numpy as np
array1d = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print(array1d[4:])? # From index 4 to last index
print(array1d[:4])? # From index 0 to 4 index
print(array1d[4:7])? # From index 4(included) up to index 7(excluded)
print(array1d[:-1])? # Excluded last element
print(array1d[:-2])? # Up to second last index(negative index)
print(array1d[::-1])? # From last to first in reverse order(negative step)
print(array1d[::-2])? # All odd numbers in reversed order
print(array1d[-2::-2])? # All even numbers in reversed order
print(array1d[::])? # All elements
```
輸出:
```
[4 5 6 7 8 9]
[0 1 2 3]
[4 5 6]
[0 1 2 3 4 5 6 7 8]
[0 1 2 3 4 5 6 7]
[9 8 7 6 5 4 3 2 1 0]
[9 7 5 3 1]
[8 6 4 2 0]
[0 1 2 3 4 5 6 7 8 9]
```
------
### 多維數(shù)組切片
對于二維數(shù)組乳讥,使用相同的語法,但它的行和列是單獨(dú)定義的廓俭。
例
```
import numpy as np
array2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("-" * 10)
print(array2d[:, 0:2])? # 2nd and 3rd col
print("-" * 10)
print(array2d[1:3, 0:3])? # 2nd and 3rd row
print("-" * 10)
print(array2d[-1::-1, -1::-1])? # Reverse an array
```
輸出:
```
----------
[[1 2]
[4 5]
[7 8]]
----------
[[4 5 6]
[7 8 9]]
----------
[[9 8 7]
[6 5 4]
[3 2 1]]
```
------
## 操作數(shù)組的維度和大小
### 轉(zhuǎn)置和翻轉(zhuǎn)
ndarray中也存在轉(zhuǎn)置函數(shù)`transpose`云石,它可以置換數(shù)組的維度。**fliplr(左右翻轉(zhuǎn))**和**flipud(上下翻轉(zhuǎn))**函數(shù)執(zhí)行類似于轉(zhuǎn)置的操作研乒,其輸出數(shù)組的維度與輸入相同汹忠。`fliplr`在左右方向上翻轉(zhuǎn)矩陣數(shù)組。`flipud`在上下方向上翻轉(zhuǎn)矩陣數(shù)組。`rot90`在軸指定的平面中將矩陣數(shù)組逆時(shí)針旋轉(zhuǎn)90度宽菜。
例:
```
import numpy as np
array2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(array2d)
print("-" * 10)
# Permute the dimensions of an array.
arrayT = np.transpose(array2d)
print(arrayT)
print("-" * 10)
# Flip array in the left/right direction.
arrayFlr = np.fliplr(array2d)
print(arrayFlr)
print("-" * 10)
# Flip array in the up/down direction.
arrayFud = np.flipud(array2d)
print(arrayFud)
print("-" * 10)
# Rotate an array by 90 degrees in the plane specified by axes.
arrayRot90 = np.rot90(array2d)
print(arrayRot90)
```
輸出:
```
[[1 2 3]
[4 5 6]
[7 8 9]]
----------
[[1 4 7]
[2 5 8]
[3 6 9]]
----------
[[3 2 1]
[6 5 4]
[9 8 7]]
----------
[[7 8 9]
[4 5 6]
[1 2 3]]
----------
[[3 6 9]
[2 5 8]
[1 4 7]]
```
------
### 拼接和堆疊
NumPy使用堆疊的概念并提供許多功能:垂直堆疊(行式)使用`vstack`谣膳,水平堆疊(列式)使用`hstack`,深度堆疊(沿第三軸)使用铅乡。`concatenate`函數(shù)通過沿給定軸追加數(shù)組來創(chuàng)建一個(gè)新數(shù)組继谚。`append`函數(shù)將一個(gè)元素追加到數(shù)組并創(chuàng)建一個(gè)新的數(shù)組副本。
例:
```
import numpy as np
array1 = np.array([[1, 2, 3], [4, 5, 6]])
array2 = np.array([[7, 8, 9], [10, 11, 12]])
# Stack arrays in sequence horizontally (column wise).
arrayH = np.hstack((array1, array2))
print(arrayH)
print("-" * 10)
# Stack arrays in sequence vertically (row wise).
arrayV = np.vstack((array1, array2))
print(arrayV)
print("-" * 10)
# Stack arrays in sequence depth wise (along third axis).
arrayD = np.dstack((array1, array2))
print(arrayD)
print("-" * 10)
# Appending arrays after each other, along a given axis.
arrayC = np.concatenate((array1, array2))
print(arrayC)
print("-" * 10)
# Append values to the end of an array.
arrayA = np.append(array1, array2, axis=0)
print(arrayA)
print("-" * 10)
arrayA = np.append(array1, array2, axis=1)
print(arrayA)
```
輸出:
```
[[ 1? 2? 3? 7? 8? 9]
[ 4? 5? 6 10 11 12]]
----------
[[ 1? 2? 3]
[ 4? 5? 6]
[ 7? 8? 9]
[10 11 12]]
----------
[[[ 1? 7]
? [ 2? 8]
? [ 3? 9]]
[[ 4 10]
? [ 5 11]
? [ 6 12]]]
----------
[[ 1? 2? 3]
[ 4? 5? 6]
[ 7? 8? 9]
[10 11 12]]
----------
[[ 1? 2? 3]
[ 4? 5? 6]
[ 7? 8? 9]
[10 11 12]]
----------
[[ 1? 2? 3? 7? 8? 9]
[ 4? 5? 6 10 11 12]]
```
------
## 代數(shù)運(yùn)算
### 算術(shù)運(yùn)算
NumPy數(shù)組的算術(shù)運(yùn)算是每個(gè)元素對應(yīng)操作的阵幸,這意味著運(yùn)算符僅應(yīng)用于相應(yīng)的元素之間花履。
例:
```
import numpy as np
array1 = np.array([[1, 2, 3], [4, 5, 6]])
array2 = np.array([[7, 8, 9], [10, 11, 12]])
print(array1 + array2)
print("-" * 20)
print(array1 - array2)
print("-" * 20)
print(array1 * array2)
print("-" * 20)
print(array2 / array1)
print("-" * 40)
print(array1 ** array2)
print("-" * 40)
```
輸出:
```
[[ 8 10 12]
[14 16 18]]
--------------------
[[-6 -6 -6]
[-6 -6 -6]]
--------------------
[[ 7 16 27]
[40 55 72]]
--------------------
[[7.? 4.? 3. ]
[2.5 2.2 2. ]]
----------------------------------------
[[? ? ? ? ? 1? ? ? ? 256? ? ? 19683]
[? ? 1048576? ? 48828125 -2118184960]]
----------------------------------------
```
------
### 標(biāo)量算術(shù)運(yùn)算
標(biāo)量操作,標(biāo)量值應(yīng)用于數(shù)組中的每個(gè)元素挚赊。
例:
```
import numpy as np
array1 = np.array([[10, 20, 30], [40, 50, 60]])
print(array1 + 2)
print("-" * 20)
print(array1 - 5)
print("-" * 20)
print(array1 * 2)
print("-" * 20)
print(array1 / 5)
print("-" * 20)
print(array1 ** 2)
print("-" * 20)
```
輸出:
```
[[12 22 32]
[42 52 62]]
--------------------
[[ 5 15 25]
[35 45 55]]
--------------------
[[ 20? 40? 60]
[ 80 100 120]]
--------------------
[[ 2.? 4.? 6.]
[ 8. 10. 12.]]
--------------------
[[ 100? 400? 900]
[1600 2500 3600]]
--------------------
```
------
### 初等數(shù)學(xué)函數(shù)
這些數(shù)學(xué)函數(shù)將任意維度的單個(gè)數(shù)組作為輸入诡壁,并返回相同維度的新數(shù)組。
| 方法? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | 描述? ? ? ? ? ? ? ? ? |
| ---------------------------------------- | ---------------------- |
| np.cos(), np.sin(), np.tan()? ? ? ? ? ? | 三角函數(shù)? ? ? ? ? ? ? |
| np.arccos(), np.arcsin(), np.arctan()? ? | 反三角函數(shù)? ? ? ? ? ? |
| np.cosh(), np.sinh(), np.tanh()? ? ? ? ? | 雙曲三角函數(shù)? ? ? ? ? |
| np.arccosh(), np.arcsinh(), np.arctanh() | 反雙曲三角函數(shù)? ? ? ? |
| np.sqrt()? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | 平方根? ? ? ? ? ? ? ? |
| np.exp()? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | 指數(shù)? ? ? ? ? ? ? ? ? |
| np.log(), np.log2(), np.log10()? ? ? ? ? | 基數(shù)為e咬腕,2和10的對數(shù)欢峰。 |
例:
```
import numpy as np
array1 = np.array([[10, 20, 30], [40, 50, 60]])
print(np.sin(array1))
print("-" * 40)
print(np.cos(array1))
print("-" * 40)
print(np.tan(array1))
print("-" * 40)
print(np.sqrt(array1))
print("-" * 40)
print(np.exp(array1))
print("-" * 40)
print(np.log10(array1))
print("-" * 40)
```
輸出:
```
[[-0.54402111? 0.91294525 -0.98803162]
[ 0.74511316 -0.26237485 -0.30481062]]
----------------------------------------
[[-0.83907153? 0.40808206? 0.15425145]
[-0.66693806? 0.96496603 -0.95241298]]
----------------------------------------
[[ 0.64836083? 2.23716094 -6.4053312 ]
[-1.11721493 -0.27190061? 0.32004039]]
----------------------------------------
[[3.16227766 4.47213595 5.47722558]
[6.32455532 7.07106781 7.74596669]]
----------------------------------------
[[2.20264658e+04 4.85165195e+08 1.06864746e+13]
[2.35385267e+17 5.18470553e+21 1.14200739e+26]]
----------------------------------------
[[1.? ? ? ? 1.30103? ? 1.47712125]
[1.60205999 1.69897? ? 1.77815125]]
----------------------------------------
```
------
### 元素?cái)?shù)學(xué)運(yùn)算
| 方法? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | 描述? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? |
| --------------------------------------------------- | -------------------------------------------------- |
| np.add(), np.subtract(), np.multiply(), np.divide() | 數(shù)組元素的四則運(yùn)算? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? |
| np.power()? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | 第一個(gè)數(shù)組元素作為底數(shù),求第二個(gè)數(shù)組中相應(yīng)元素的冪 |
| np.remainder()? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | 求輸入數(shù)組中相應(yīng)元素相除后的余數(shù)? ? ? ? ? ? ? ? ? |
| np.reciprocal()? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | 求輸入數(shù)組中相應(yīng)元素的倒數(shù)? ? ? ? ? ? ? ? ? ? ? ? |
| np.sign(), np.abs()? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | 返回?cái)?shù)字符號(正負(fù)號)和絕對值涨共。? ? ? ? ? ? ? ? ? |
| np.floor(), np.ceil()? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | 返回向上取整值和向下取整值? ? ? ? ? ? ? ? ? ? ? ? |
| np.round()? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | 四舍五入到給定精度的值(默認(rèn)精度為0位)? ? ? ? ? ? |
例:
```
import numpy as np
array1 = np.array([[10, 20, 30], [40, 50, 60]])
array2 = np.array([[2, 3, 4], [4, 6, 8]])
array3 = np.array([[-2, 3.5, -4], [4.05, -6, 8]])
print(np.add(array1, array2))
print("-" * 40)
print(np.power(array1, array2))
print("-" * 40)
print(np.remainder((array2), 5))
print("-" * 40)
print(np.reciprocal(array3))
print("-" * 40)
print(np.sign(array3))
print("-" * 40)
print(np.ceil(array3))
print("-" * 40)
print(np.round(array3))
print("-" * 40)
```
輸出:
```
[[12 23 34]
[44 56 68]]
----------------------------------------
[[? ? ? ? 100? ? ? ? 8000? ? ? 810000]
[? ? 2560000 -1554869184 -1686044672]]
----------------------------------------
[[2 3 4]
[4 1 3]]
----------------------------------------
[[-0.5? ? ? ? 0.28571429 -0.25? ? ? ]
[ 0.24691358 -0.16666667? 0.125? ? ]]
----------------------------------------
[[-1.? 1. -1.]
[ 1. -1.? 1.]]
----------------------------------------
[[-2.? 4. -4.]
[ 5. -6.? 8.]]
----------------------------------------
[[-2.? 4. -4.]
[ 4. -6.? 8.]]
----------------------------------------
```
------
### 聚合和統(tǒng)計(jì)函數(shù)
| 方法? ? ? ? ? ? ? ? ? ? | 描述? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? |
| ------------------------ | -------------------------------------- |
| np.mean()? ? ? ? ? ? ? ? | 計(jì)算沿指定軸的算術(shù)平均值纽帖。? ? ? ? ? ? |
| np.std()? ? ? ? ? ? ? ? | 計(jì)算沿指定軸的標(biāo)準(zhǔn)偏差。? ? ? ? ? ? ? |
| np.var()? ? ? ? ? ? ? ? | 計(jì)算沿指定軸的方差举反。? ? ? ? ? ? ? ? ? |
| np.sum()? ? ? ? ? ? ? ? | 給定軸上的數(shù)組元素的總和懊直。? ? ? ? ? ? |
| np.prod()? ? ? ? ? ? ? ? | 返回給定軸上的數(shù)組元素的乘積。? ? ? ? |
| np.cumsum()? ? ? ? ? ? ? | 返回給定軸上元素的累積和火鼻。? ? ? ? ? ? |
| np.cumprod()? ? ? ? ? ? | 返回給定軸上元素的累積乘積室囊。? ? ? ? ? |
| np.min(), np.max()? ? ? | 返回沿軸元素的最小值/最大值。? ? ? ? ? |
| np.argmin(), np.argmax() | 返回沿軸元素最小值/最大值的索引魁索。? ? ? |
| np.all()? ? ? ? ? ? ? ? | 測試沿給定軸的所有數(shù)組元素是否為True融撞。 |
| np.any()? ? ? ? ? ? ? ? | 測試沿給定軸的任何數(shù)組元素是否為True。 |
例:
```
import numpy as np
array1 = np.array([[10, 20, 30], [40, 50, 60]])
print("Mean: ", np.mean(array1))
print("Std: ", np.std(array1))
print("Var: ", np.var(array1))
print("Sum: ", np.sum(array1))
print("Prod: ", np.prod(array1))
```
輸出:
```
Mean:? 35.0
Std:? 17.07825127659933
Var:? 291.6666666666667
Sum:? 210
Prod:? 720000000
```
------
## 常用的條件和邏輯表達(dá)式函數(shù)
### 使用where()更新數(shù)組
`where()` 函數(shù)用于根據(jù)特定條件從數(shù)組中選擇值粗蔚。
例:
```
import numpy as np
before = np.array([[1, 2, 3], [4, 5, 6]])
# If element is less than 4, mul by 2 else by 3
after = np.where(before < 4, before * 2, before * 3)
print(after)
```
輸出:
```
[[ 2? 4? 6]
[12 15 18]]
```
------
### 使用select()更新數(shù)組
`select()` 函數(shù)返回根據(jù)條件選中的元素組成的數(shù)組尝偎。
例:
```
import numpy as np
before = np.array([[1, 2, 3], [4, 5, 6]])
# If element is less than 4, mul by 2 else by 3
after = np.select([before < 4, before], [before * 2, before * 3])
print(after)
```
輸出:
```
[[ 2? 4? 6]
[12 15 18]]
```
------
### 使用choose()構(gòu)造數(shù)組
從索引數(shù)組和一組數(shù)組中選擇元素構(gòu)造一個(gè)數(shù)組。
例:
```
import numpy as np
before = np.array([[0, 1, 2], [2, 0, 1], [1, 2, 0]])
choices = [5, 10, 15]
after = np.choose(before, choices)
print(after)
print("-" * 10)
before = np.array([[0, 0, 0], [2, 2, 2], [1, 1, 1]])
choice1 = [5, 10, 15]
choice2 = [8, 16, 24]
choice3 = [9, 18, 27]
after = np.choose(before, (choice1, choice2, choice3))
print(after)
```
輸出:
```
[[ 5 10 15]
[15? 5 10]
[10 15? 5]]
----------
[[ 5 10 15]
[ 9 18 27]
[ 8 16 24]]
```
------
### 邏輯運(yùn)算
`logical_or(x1,x2)`函數(shù)按元素計(jì)算x1 OR x2的真值鹏控。`logical_and(x1,x2`)函數(shù)按元素計(jì)算x1 AND x2的真值致扯。`logical_not(x)`函數(shù)按元素計(jì)算NOT x的真值。
例:
```
import numpy as np
thearray = np.array([[10, 20, 30], [14, 24, 36]])
print(np.logical_or(thearray < 10, thearray > 15))
print("-" * 30)
print(np.logical_and(thearray < 10, thearray > 15))
print("-" * 30)
print(np.logical_not(thearray < 20))
print("-" * 30)
```
輸出:
```
[[False? True? True]
[False? True? True]]
------------------------------
[[False False False]
[False False False]]
------------------------------
[[False? True? True]
[False? True? True]]
------------------------------
```
------
## 標(biāo)準(zhǔn)集合運(yùn)算
標(biāo)準(zhǔn)集合運(yùn)算包括并集(屬于兩個(gè)輸入數(shù)組中任意一個(gè)數(shù)組的元素)当辐,交集(同時(shí)屬于兩個(gè)輸入數(shù)組的元素)和差(在數(shù)組1中而不在數(shù)組2中的元素)抖僵,對應(yīng)地由函數(shù) `np.union1d()`,`np.intersect1d()`和`np.setdiff1d()`實(shí)現(xiàn)缘揪。
例:
```
import numpy as np
array1 = np.array([[10, 20, 30], [14, 24, 36]])
array2 = np.array([[20, 40, 50], [24, 34, 46]])
# Find the union of two arrays.
print(np.union1d(array1, array2))
# Find the intersection of two arrays.
print(np.intersect1d(array1, array2))
# Find the set difference of two arrays.
print(np.setdiff1d(array1, array2))
```
輸出:
```
[10 14 20 24 30 34 36 40 46 50]
[20 24]
[10 14 30 36]
```
## 小結(jié)
在本教程中耍群,我們了解了**NumPy **庫的幾個(gè)主要方面义桂,并熟悉了**NumPy**的N維數(shù)組數(shù)據(jù)結(jié)構(gòu)和函數(shù)范圍。我們看到世吨,由于ndarray澡刹,我們可以擴(kuò)展Python的功能,使其成為適合科學(xué)計(jì)算和數(shù)據(jù)分析的語言耘婚。
我們討論了用于創(chuàng)建和操作數(shù)組的函數(shù),包括用于從數(shù)組中提取元素的索引和切片函數(shù)陆赋。
因此沐祷,對于想要進(jìn)行數(shù)據(jù)分析的人來說,了解**NumPy **至關(guān)重要攒岛。
------
原文:[numpy tutorial with examples and solutions](https://www.pythonprogramming.in/numpy-tutorial-with-examples-and-solutions.html)