這3個函數(shù),是你學(xué)習(xí)Numpy的基礎(chǔ)!
1. 本文介紹
Ⅰ ndarray數(shù)組與列表的相互轉(zhuǎn)化; Ⅱ ndarray數(shù)組的數(shù)據(jù)類型轉(zhuǎn)化; Ⅲ 改變ndarray數(shù)組的形狀;
2. ndarray數(shù)組與列表的相互轉(zhuǎn)化
① 列表轉(zhuǎn)數(shù)組:直接將一個列表傳入array()函數(shù)中
list1 = list(range(10))
print(list1)
array1 = np.array(list1)
print(array1)

② 數(shù)組轉(zhuǎn)列表:調(diào)用數(shù)組的tolist()方法
array2 = np.arange(10)
print(array2)
list2 = array2.tolist()
print(list2)

3. ndarray數(shù)組的數(shù)據(jù)類型轉(zhuǎn)化
① numpy中常用的的數(shù)據(jù)類型
② 使用dtype原地修改數(shù)組的數(shù)據(jù)類型,會出現(xiàn)什么問題?
x = np.array([1.2,3.4,5.6],dtype=np.float64)
print(x)
print(x.dtype)
print(x.nbytes)
# --------------------------------------------
x.dtype="float32"
print(x)
print(x.nbytes)
# --------------------------------------------
x.dtype="float16"
print(x)
print(x.nbytes)

③ 使用astype()函數(shù)修改數(shù)組的數(shù)據(jù)類型:相當(dāng)于新創(chuàng)建了一個數(shù)組
z = np.array([1.5,3.7,4.8])
print(z)
print(z.dtype)
zz = z.astype(np.float32)
print(zz)
print(zz.dtype)

4. 改變ndarray數(shù)組的形狀
① 使用numpy中的reshape()函數(shù)修改數(shù)組對象
xx = np.arange(10).reshape(2,5)
xxx = np.reshape(xx,(5,2))
print(xxx)

② 使用數(shù)組對象的reshape()方法修改數(shù)組對象
yy = np.arange(10).reshape(2,5)
print(yy)

③ 改變數(shù)組形狀時,如果維度大于1,可以將“最后一個維度”設(shè)置為-1
p = np.arange(6).reshape(2,3)
print(p)
q = np.arange(6).reshape(2,-1)
print(q)

更多閱讀
特別推薦

點擊下方閱讀原文加入社區(qū)會員
評論
圖片
表情
