numpy學習筆記(代碼)

import numpy as np
import random
#用numpy生成數組,t1,t2,t3
t1 = np.array([0, 1, 2, 3, 4])
print(t1,'\n')

t2 = np.array(range(5))
print(t2,'\n')

t3 = np.arange(5)
print(t3,'\n')

#用numpy生成的數組的類型爲<class 'numpy.ndarray'>
print(type(t3),'\n')

#dtype顯示的是數組元素的類型,
# 有int(8,16,32,64),float(16,32,64,128),uint(8,16,32,64),complex(64,128),bool這麼多
print(t3.dtype,'\n')

"""創建不同類型的數組,用dtype參數"""
#float64類型
t4 = np.array(range(10), dtype=float)
print(t4)
print(t4.dtype,'\n')         #爲float64是因爲電腦爲64位

#bool類型
t5 = np.array([1, 0, 0, 1, 0, 1], dtype=bool)
print(t5)
print(t5.dtype,'\n')

"""數據的類型轉換,用astype("要轉換的類型")方法"""

#bool轉int8
t6 = t5.astype("int8")
print(t6, t6.dtype,'\n')

"""修改小數的位數,用roung方法"""
t7 = np.array([random.random() for i in range(10)])
print(t7, t7.dtype,'\n')
#取3位小數
t8 = np.round(t7,3)
print(t8, t8.dtype,'\n')

#不在numpy中的取小數,取3位
print(round(random.random(),3),'\n')


"""數組的形狀"""
#查看數組的形狀  .shape
#一維
d1 = np.array(range(12))
print(d1,d1.shape,'\n')
#二維
d2 = np.array([[1, 2, 3], [4, 5, 6]])
print(d2,d2.shape,'\n')

"""修改數組的形狀 reshape()"""
l = np.array([0,1,2,3,4,5,6,7,8,9,10,11])
#二維
d3 = l.reshape(3, 4)
print(d3,d3.shape,'\n')
#三維
d4 = np.array(range(24)).reshape(2,3,4)
print(d4, d4.shape,'\n')
#4維
d5 = np.array(range(48)).reshape(2,2,3,4)
print(d5,d5.shape,'\n')

"""將多維數組展開,flatten()"""
#用reshape展開
d6 = d5.reshape(d5.shape[0]*d5.shape[1]*d5.shape[2]*d5.shape[3],)
print(d6, d6.shape,'\n')

d7 = d5.flatten()
print(d7, d7.shape,'\n')

"""數組與數字,數組與數組進行計算"""
a1 = np.array(range(12)).reshape(3,4)
print('數組與數字:\n',a1,'\n')
print(a1+5,'\n')
print(a1-5,'\n')
print(a1*5,'\n')
print(a1/5,'\n')

#數組與數組進行計算是,維度要基本一致,維度不一致時,有時可以計算,有時不可以
print('數組與數組:\n',a1+a1,'\n')
print(a1-a1,'\n')
print(a1*a1,'\n')
print(a1/a1,'\n')
"""數據的索引與切片"""
import numpy as np

t1 = np.array(range(24)).reshape((4, 6))
print(t1, '\n')
#取行
print(t1[1:], '\n')     #取1到最後一行
#取不連續的行
print(t1[[0, 2, 3]], '\n')

#取列
print(t1[:, 0], '\n')  #取第0列

print(t1[:, [2, 4, 5]], '\n') #取多列

#取多行多列
print(t1[[0,2,3],[1,4,5]], '\n')



"""numpy中數值的修改"""

#將數組中下於10的數字替換成3
print(t1, '\n')
print(t1[t1<10], '\n')  #打印出小於10的元素
t1[t1<10] = 3           #將小於10的數賦值爲3
print(t1, '\n')

"""numpy中的三元運算符where"""
t2 = np.where(t1 < 10, 0, 20, '\n')  #將t1中小於10的替換成0,否則(大於等於10)替換成20
print(t2)

"""numpy中的裁剪clip"""
t3 = t1.clip(10,18)  #小於10的會被替換爲10,大於18的會被替換成18
print(t3, '\n')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章