# 資料D1~3:Numpy 陣列的定義與屬性/資料型態/初始化
## ndarray屬性
ndarray.ndim: 陣列有多少維度
ndarray.shape: 每個維度的大小
ndarray.size: 陣列當中有幾個元素
ndarray.dtype: 陣列中的資料型態
ndarray.itemsize: 陣列中每個元素佔用的空間
ndarray.data: 陣列所存在的記憶體位置
type(ndarray): 資料型態<class 'numpy.ndarray'>
len(ndarray):陣列長度(指最外層的)
## array轉換為list
多維的部分會被攤平
list(a) 變成array包在list裡面
[array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9]), array([10, 11, 12, 13, 14])]
tolist() 變成list包在list裡面
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]
## ndarray特性
使用更少的空間儲存資料
對於元素的查找更加快速高效
可以更好地表示數學中的向量/矩陣
支援了矩陣相關的數學運算
## range/np.arrange/np.linspace
https://www.itread01.com/content/1536994702.html
range(start, stop, step)
np.arrange(start, stop, step)
linspace(start, stop, num=, endpoint=True, retstep=False, dtype=None)
## dtype 與 itemsize
在陣列的屬性當中,有兩個跟型態有關:
ndarray.dtype: 陣列中的資料型態(所有資料型態都一樣)
ndarray.itemsize: 陣列中每個元素佔用的空間
numpy比python有更彈性的指定數字空間大小的種類
例如int64占用8 bytes
型態判斷:
type(a) == int64
a.dtype is "int64"
a.dtype is np.int64
NumPy 型態的定義是一個 np.dtype 的物件,包含「型態名稱」、「表示範圍」及「儲存空間」等等的資訊
用== 只要某一樣符合即可
用is 則需要全部都正確,要跟np.dtype比
print(a.dtype == 'int64') # True
print(a.dtype is 'int64') # False
print(a.dtype is np.dtype('int64')) # True
## 建立array

### 從python物件得到
np.array(.....) ...可為list tuple...
若是dic可能會有問題
裡面型態若有不同,則預設選擇範圍最大的
numpy.array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, like=None)
object:必填,任何 array_like 物件
dtype:指定轉成陣列後的元素型態
copy:預設為 True,是否產生一個新的物件
order:指定元素在記憶體中的儲存方式
https://numpy.org/doc/stable/reference/generated/numpy.array.html
### 固定大小初始值
np.zeros((2, 3))
建立由 0 組成的 2x3 陣列
np.ones((2, 3))
建立由 1 組成的 2x3 陣列
np.full((2, 3), 9)
建立由 9 組成的 2x3 陣列
np.empty((2, 3))
產生接近0的隨機數的陣列,可用於單純初始化
### 固定樣式數值
np.arange( 10, 30, 5 ) 等差 起始/終點(預設不包含)/間隔
array([10, 15, 20, 25])
np.linspace( 0, 2, 3 ) 等差 起始/終點(預設包含)/個數
array([0. 1. 2.])
np.logspace( 0, 2, 3 ) 等比 同上,顯示的是次方
array([1. 10. 100.])
### 亂數
from numpy.random import default_rng
rng = default_rng()
normal = rng.standard_normal((3,2))
random = rng.random((3,2))
integers = rng.integers(0, 10, size=(3,2))
可用a.round()或是np.round(a)來捨去整數
https://numpy.org/doc/stable/reference/random/index.html?highlight=random#module-numpy.random
## Array特性
### 一開始就固定大小
記憶體存取效能較佳
### 結構化Array
建立結構化陣列可透過 dictionary 型別的資料建立 np.dtype 物件,並指定 dtype 給陣列。
資料型別可以使用 Python 的資料型別、NumPy 的資料型別、或是字母代表的型別皆可。
###### tags: `資料科學馬拉松` `python`