---
title: Python Module - Numpy
tags: python, module, numpy
---
[TOC]
---
# Python Module - Numpy
```python=
# Try it
import numpy as np
```
:::danger
If you are not have numpy module, install it.
pip install numpy
:::
## Function
- `np.array( list )`
```python=
A = np.array([1, 2, 3])
B = np.array([4, 5, 6])
# 基本運算
A + B #array([5, 7, 9])
A - B #array([-3, -3, -3])
A B #array([ 4, 10, 18])
A / B #array([0.25, 0.4 , 0.5 ])
A 2 #array([1, 4, 9], dtype=int32)
# 以上的運算為元素對元素的運算,故大小需相同
# 比較運算
C = np.arange(-2, 3) #array([-2, -1, 0, 1, 2])
C >= 0 #array([False, False, True, True, True])
# 其餘以此類推
# 透過比較運算取代元素
C[C < 0] = 99 #array([99, 99, 0, 1, 2])
```
- `np.arange( start, end, incremnt )`
- range is `[start, end)`
```python=
a = np.arange(5) #array([0, 1, 2, 3, 4])
b = np.arange(7, 4, -1) #array([7, 6, 5])
```
- `np.ones( shape, dtype=None, order='C' )`
- shape: 矩陣大小(M,N)
- dtype: 元素型別,Default is float64
```python=
np.ones( (2,2), dtype=int )
#array([[1, 1], [1, 1]])
```
- `np.linspace( start, stop, num=50, endpoint=True )`
- (start, stop) 等分 num 個點
- endpoint 決定 stop 是否納入
- `np.repeat( value, repeats, axis=None )`
- `Return`: Array contains `repeats` times value
```python=
# sales 2017
sales_2017 = pd.DataFrame([['chair',20],['sofa',24],['table',15]], columns=['product','sales_units'])
# sales 2018
sales_2018 = pd.DataFrame([['chair',25],['sofa',10],['shelf',10]], columns=['product','sales_units'])
# add year column in data frame 2017
sales_2017['year'] = np.repeat(2017, sales_2017.shape[0])
# add year column in data frame 2018
sales_2018['year'] = np.repeat(2018, sales_2018.shape[0])
sales = pd.concat([sales_2017,sales_2018], ignore_index=True)
```
- `np.linalg.inv( array )`
- 找 `array` 的inverse
- `np.linalg.norm( array )`
- 取`array`的長度
- `np.linalg.det( array )`
- 取`array`的determin
- `np.loadtxt( filename.txt )`
- `np.dot( A, B )`
- Do that A dot B
- `np.concatenate( (a1, a2, ...), axis=0, out=None, dtype=None, casting="same_kind" )`
- Join a sequence of arrays along an existing axis
- `out`
- If provided, the destination to place the result.
- `np.apply_along_axis(func1d, axis, arr, *args, **kwargs)`
- Apply a function to 1-D slices along the given axis.
#### Math Function
- `np.sin( array )`
- `np.cos( array )`
- `np.exp( array )`
- `np.log( array )`
- `numpy.polyfit( x, y, deg, rcond=None, full=False, w=None, cov=False )`
- Outputs a polynomial of degree deg that fits the points (x,y), minimizing the square error
- `Return`: $[c_{deg}, c_{deg-1}, ..., c_1, c_0]$
## Random Function
- `np.random.randint( low, high=None, size=None, dtype='l' )`
- `Return`: Array of random int in `[low, high)`
- If `high` is None, then range is `[0, low)`
- If `size` is None, then default size is one
- `np.random.choice( array, size=None, replace=True, p=None )`
- `Return`: A random sample from a given array
- `p`: Probability
- If `size` is None, then default size is one
```python=
# roll a dice
np.random.choice([1,2,3,4,5,6])
# roll a dice 10 times
np.random.choice([1,2,3,4,5,6], size=10)
# 0-->head, 1-->tail
# toss a biased coin (80% probability of obtain head - 20% tail)
np.random.choice([0,1],p=[0.8,0.2])
```
- `numpy.random.permutation(x)`
- `Return` ndarray
- `x` is array-like instance
- `np.random.binomial( n, p, size=None )`
## Array Function
- `dot( array )`
- 矩陣乘法
- `sum( axis=None )`
- `axis`
- `None`: 矩陣各元素總和
- `0`: 加總每一欄
- `1`: 加總每一列
- `min()`
- 矩陣最小值
- `max()`
- 矩陣最大值
- `mean()`
- 矩陣平均值
- `reshape( row, column )`
- 改變矩陣大小
- elements of array == row * column
- `transpose()`
- 轉置矩陣
- Use two bracket pairs instead of one. This creates a 2D array, which can be transposed, unlike the 1D array you create if you use one bracket pair.
```python=
A = np.array([[5,4]]) #array([[5, 4]])
A_T = A.transpose()
"""
array([[5],
[4]])
"""
```
- astype( dtype )
- 將矩陣元素型別轉換為`dtype`
- `dtype`: `'int'`, `'float'`, ...
- flatten( order='C' )
- `Return`: a copy of the array collapsed into one dimension .
- `order`
- `'C'` means to flatten in row-major (C-style) order.
```python=
a = np.array([[2, 4], [6,8], [1,3], [5,7]], dtype='int')
a.flatten() # array([2, 4, 6, 8, 1, 3, 5, 7])
```
#### Array Operator
```python=
a = np.array([[2, 4], [6,8], [1,3], [5,7]], dtype='int')
a[2, :] # [1,3]
a[:, 1] # [4, 8, 3, 7]
a[1, 1] # 8
```