Numpy常見用法
基礎(chǔ)
0.導(dǎo)入numpy
import numpy as np
1.查看numpy版本
np.__version__
'1.16.5'
創(chuàng)建數(shù)組
2.創(chuàng)建一維、二維、三維數(shù)組
列表可用元祖替換,效果一樣
arr_1d=np.array([1,2,3])
arr_2d=np.array([[1,2,3],[4,5,6]])
arr_3d=np.array([[[1,2],[3,4],[5,6]],[[1,2],[3,4],[5,6]]])
arr_3d
array([[[1, 2],
[3, 4],
[5, 6]],
[[1, 2],
[3, 4],
[5, 6]]])
3.創(chuàng)建全零數(shù)組
arr_zero=np.zeros(9)
arr_zero_2d=np.zeros((2,3))
arr_zero_3d=np.zeros((2,3,4))
arr_zero_3d
array([[[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]],
[[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]]])
4.創(chuàng)建全1數(shù)組
arr_one=np.ones(9)
arr_one_2d=np.ones((2,3))
arr_one_3d=np.ones((2,3,4))
arr_one_3d
array([[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]],
[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]]])
4.創(chuàng)建等差數(shù)組
np.arange(5)
np.arange(9).reshape(3,-1)
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
5.創(chuàng)建單位矩陣
單位矩陣是方陣,所以只需填入方陣的階數(shù)即可
np.eye(3)
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
6.創(chuàng)建等間隔數(shù)組
np.linspace(1,10,num=10)#不同于arange,區(qū)間為左閉右閉
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
7.創(chuàng)建二維隨機(jī)數(shù)組
np.random.rand(2,3)
array([[0.72185898, 0.92349404, 0.76279896],
[0.47867698, 0.13746813, 0.09909993]])
#正太分布的隨機(jī)數(shù)
np.random.randn(2,3)
array([[ 0.49403566, 0.64345745, -0.51435898],
[-0.94412068, 0.04755553, 1.0672753 ]])
np.random.normal(0,1,10)
array([ 0.73524079, -0.51625073, 2.09953668, 0.46101246, 0.53788767,
0.47686257, 0.78645654, 1.24695482, -0.90228324, -0.18597803])
8.創(chuàng)建二維隨機(jī)整數(shù)數(shù)組
np.random.randint(1,5,(2,3))#取值區(qū)間左閉右開
array([[3, 3, 4],
[3, 4, 2]])
9.根據(jù)自定義函數(shù)創(chuàng)建數(shù)組
np.fromfunction(lambda i,j:i+j,(2,3))
array([[0., 1., 2.],
[1., 2., 3.]])
數(shù)組運(yùn)算 保證維度相同
10.一維數(shù)組運(yùn)算
加減乘除 取余 內(nèi)積
a=np.arange(1,5)
b=a*10
a,b
(array([1, 2, 3, 4]), array([10, 20, 30, 40]))
a+b
a-b
a*b
a/b
a%b
array([1, 2, 3, 4], dtype=int32)
np.dot(a,b)
a.dot(b)
300
11.二維數(shù)組運(yùn)算
加減乘除 取余 矩陣乘法(需滿足矩陣維度要求)
c=a.reshape(2,-1)
d=c+2
c,d
(array([[1, 2],
[3, 4]]), array([[3, 4],
[5, 6]]))
c+d
c-d
c*d
c/d
c%d
array([[1, 2],
[3, 4]], dtype=int32)
np.dot(c,d)
array([[13, 16],
[29, 36]])
c.dot(d)
array([[13, 16],
[29, 36]])
將二維數(shù)組變換成矩陣,可直接用*
C=np.mat(c)
D=np.mat(d)
print(type(c),type(C))
<class 'numpy.ndarray'> <class 'numpy.matrix'>
C*D
matrix([[13, 16],
[29, 36]])
矩陣的其他運(yùn)算:數(shù)乘、轉(zhuǎn)置、求逆
C*2
C.T
matrix([[1, 3],
[2, 4]])
np.linalg.inv(C)
matrix([[-2. , 1. ],
[ 1.5, -0.5]])
數(shù)學(xué)函數(shù)
12.三角函數(shù)
print(a)
np.sin(a)
np.cos(a)
np.tan(a)
np.tanh(a)
np.arcsin(a)#求反函數(shù)時確保輸入的列表值在0-1范圍內(nèi),超出范圍則輸出為nan
np.arccos(a)
[1 2 3 4]
array([ 0., nan, nan, nan])
13.以自然e對數(shù)為底數(shù)的指數(shù)函數(shù)
np.exp(a)
array([ 2.71828183, 7.3890561 , 20.08553692, 54.59815003])
14.數(shù)組開方、平方、立方、對數(shù)
np.sqrt(a)
np.square(a)
np.power(a,3)
np.log(a) #log10, log2, log1p, emath.log
array([0. , 0.69314718, 1.09861229, 1.38629436])
數(shù)組切片和索引
15.一維數(shù)組索引
print(a)
a[0]
a[-1]
a[:-1]
a[:2]
a[::-1]
a[::-2]
[1 2 3 4]
array([4, 2])
16.二維數(shù)組索引和切片
c=np.arange(12).reshape(4,3)
print(c)
c[1]#某一行
c[1,:]#同上
c[[1,0]]#某些行
c[:,1]#某一列
c[:,[1,0]]#某些列
c[1:3,:]#切片某些連續(xù)行
c[::2,:]#每隔兩行取行
c[::2,::2]#行列間隔均為2
c[[2,1,3]][:,[1,0]]#選取特定行和列組成的數(shù)組,按照給定行列順序排列
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
array([[ 7, 6],
[ 4, 3],
[10, 9]])
print(c)
c[1,1]#某一位置數(shù)值
c[[1,0,0],[0,1,0]]#選擇多個位置,如(1,0),(0,1),(0,0)處的數(shù)值
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
array([3, 1, 0])
數(shù)組形狀操作
17.查看更改數(shù)組形狀
c.shape
(4, 3)
c.reshape(-1,4)#不改變c的形狀
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
c_copy=c.copy()
c_copy.shape
(4, 3)
c_copy.resize(3,4)#改變c_copy形狀,參數(shù)不能輸入負(fù)數(shù)
c_copy.shape
(3, 4)
18.展平數(shù)組
print(c)
c.ravel()
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
c.flatten()
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
19.數(shù)組拼接
np.random.seed(0)
arr1=np.random.randint(1,10,(3,3))
arr2=np.random.randint(10,size=(3,3))
縱向拼接(垂直拼接)
np.vstack((arr1,arr2))
array([[6, 1, 4],
[4, 8, 4],
[6, 3, 5],
[7, 6, 8],
[8, 1, 6],
[7, 7, 8]])
np.r_[arr1,arr2]
array([[6, 1, 4],
[4, 8, 4],
[6, 3, 5],
[7, 6, 8],
[8, 1, 6],
[7, 7, 8]])
橫向拼接(水平拼接)
np.hstack((arr1,arr2))
array([[6, 1, 4, 7, 6, 8],
[4, 8, 4, 8, 1, 6],
[6, 3, 5, 7, 7, 8]])
np.c_[arr1,arr2]
array([[6, 1, 4, 7, 6, 8],
[4, 8, 4, 8, 1, 6],
[6, 3, 5, 7, 7, 8]])
按軸拼接(axis=0表示縱向拼接,axis=1表示橫向拼接)
np.concatenate([arr1,arr2],axis=0)
array([[6, 1, 4],
[4, 8, 4],
[6, 3, 5],
[7, 6, 8],
[8, 1, 6],
[7, 7, 8]])
np.concatenate([arr1,arr2],axis=1)
array([[6, 1, 4, 7, 6, 8],
[4, 8, 4, 8, 1, 6],
[6, 3, 5, 7, 7, 8]])
20.數(shù)組分割
分割后數(shù)組形狀不變
橫向分割
print(c)
np.hsplit(c,3) #橫向分割,均分3部分
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
[array([[0],
[3],
[6],
[9]]), array([[ 1],
[ 4],
[ 7],
[10]]), array([[ 2],
[ 5],
[ 8],
[11]])]
np.hsplit(c,[1])#按照指定某一列分割
np.hsplit(c,[1,2])#按照指定某些列分割
[array([[0],
[3],
[6],
[9]]), array([[ 1],
[ 4],
[ 7],
[10]]), array([[ 2],
[ 5],
[ 8],
[11]])]
縱向分割
np.vsplit(c,2) #縱向分割,均分2部分
[array([[0, 1, 2],
[3, 4, 5]]), array([[ 6, 7, 8],
[ 9, 10, 11]])]
np.vsplit(c,[1,3])#按照指定列劃分
[array([[0, 1, 2]]), array([[3, 4, 5],
[6, 7, 8]]), array([[ 9, 10, 11]])]
數(shù)組排序
np.random.seed(0)
a=np.random.randint(12,size=(3,4))
a
array([[ 5, 0, 3, 11],
[ 3, 7, 9, 3],
[ 5, 2, 4, 7]])
21.按軸返回最大最小值
np.max(a,axis=0)
a.max(0)#axis可省去,直接填軸數(shù)
array([ 5, 7, 9, 11])
np.max(a,axis=1)
a.max(1)
array([11, 9, 7])
np.min(a,axis=0)
a.min(axis=0)
array([3, 0, 3, 3])
np.min(a,axis=1)
a.min(axis=1)
array([0, 3, 2])
22.返回最值索引
#返回每一列中的最大值的行索引號,即垂直方向的各個最大值對應(yīng)的行索引
np.argmax(a,axis=0)
array([0, 1, 1, 0], dtype=int32)
#返回每一行中的最大值的列索引號,即水平方向的各個最大值對應(yīng)的列索引
np.argmax(a,axis=1)
array([3, 2, 3], dtype=int32)
23.按軸排序
print(a)
np.argsort(a,axis=0)#返回按行排序的索引,各列單獨(dú)排序,默認(rèn)升序
[[ 5 0 3 11]
[ 3 7 9 3]
[ 5 2 4 7]]
array([[1, 0, 0, 1],
[0, 2, 2, 2],
[2, 1, 1, 0]], dtype=int32)
np.argsort(a,axis=1)#返回按列排序的索引,各行單獨(dú)排序,默認(rèn)升序
array([[1, 2, 0, 3],
[0, 3, 1, 2],
[1, 2, 0, 3]], dtype=int32)
數(shù)組統(tǒng)計(jì)
24.統(tǒng)計(jì)數(shù)組各行各列中位數(shù)、算術(shù)均值、加權(quán)平均值、方差、標(biāo)準(zhǔn)差
print(a)
[[ 5 0 3 11]
[ 3 7 9 3]
[ 5 2 4 7]]
中位數(shù)
np.median(a,axis=0)
np.median(a,axis=1)
# a.median(0) 為什么沒有中位數(shù)屬性?而均值有
array([4. , 5. , 4.5])
算術(shù)平均值
np.mean(a,axis=0)
np.mean(a,axis=1)
a.mean(axis=0)
a.mean(1)
array([4.75, 5.5 , 4.5 ])
加權(quán)平均值
np.average(a,axis=0)
np.average(a,axis=1)
# a.average(axis=0) 也沒有average屬性?
array([4.75, 5.5 , 4.5 ])
方差
np.var(a,axis=0)
np.var(a,axis=1)
a.var(0)
a.var(1)
array([16.1875, 6.75 , 3.25 ])
標(biāo)準(zhǔn)差
np.std(a,axis=0)
np.std(a,axis=1)
a.std(0)
a.std(1)
array([4.02336923, 2.59807621, 1.80277564])
進(jìn)階
25.創(chuàng)建一個邊界值為1,其余為0的二維數(shù)組
arr=np.ones((5,5))
arr[1:-1,1:-1]=0
arr
array([[1., 1., 1., 1., 1.],
[1., 0., 0., 0., 1.],
[1., 0., 0., 0., 1.],
[1., 0., 0., 0., 1.],
[1., 1., 1., 1., 1.]])
26.使用數(shù)字0將全為1的5*5二維數(shù)組包圍
Z = np.ones((5, 5))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
Z
array([[0., 0., 0., 0., 0., 0., 0.],
[0., 1., 1., 1., 1., 1., 0.],
[0., 1., 1., 1., 1., 1., 0.],
[0., 1., 1., 1., 1., 1., 0.],
[0., 1., 1., 1., 1., 1., 0.],
[0., 1., 1., 1., 1., 1., 0.],
[0., 0., 0., 0., 0., 0., 0.]])
27. 創(chuàng)建一個 5x5 的二維數(shù)組,并設(shè)置值 1, 2, 3, 4 落在其對角線下方
Z = np.diag(1+np.arange(4), k=-1)
Z
array([[0, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[0, 2, 0, 0, 0],
[0, 0, 3, 0, 0],
[0, 0, 0, 4, 0]])
28. 創(chuàng)建一個 10x10 的二維數(shù)組,并使得 1 和 0 沿對角線間隔放置
Z = np.zeros((10, 10), dtype=int)
Z[1::2, ::2] = 1
Z[::2, 1::2] = 1
Z
array([[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0]])
29.創(chuàng)建一個0-10的一維數(shù)組,并將(1,9]之間的數(shù)反轉(zhuǎn)成負(fù)數(shù)
np.random.seed(0)
z=np.random.randint(11,size=10)
z[(z>1)&(z<=9)]*=-1
z
array([-5, 0, -3, -3, -7, -9, -3, -5, -2, -4])
np.where((z>1)&(z<=9),-z,z)
array([-5, 0, -3, -3, -7, -9, -3, -5, -2, -4])
30.找出兩個一維數(shù)組中相同的元素
np.random.seed(1)
z1=np.random.randint(1,10,10)
z2=np.random.randint(1,10,10)
z1,z2
(array([6, 9, 6, 1, 1, 2, 8, 7, 3, 5]), array([6, 3, 5, 3, 5, 8, 8, 2, 8, 1]))
np.intersect1d(z1,z2)
array([1, 2, 3, 5, 6, 8])
31. 使用 NumPy 打印昨天、今天、明天的日期
yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
today = np.datetime64('today', 'D')
tomorrow = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
print("yesterday: ", yesterday)
print("today: ", today)
print("tomorrow: ", tomorrow)
yesterday: 2019-12-11
today: 2019-12-12
tomorrow: 2019-12-13
32. 使用不同的方法去提取一個隨機(jī)數(shù)組的整數(shù)部分
np.random.seed(1)
Z = np.random.uniform(0, 10, 10)
print("原始值: ", Z)
print("方法 0: ", Z - Z % 1)
print("方法 1: ", Z // 1)
print("方法 2: ", np.floor(Z))
print("方法 3: ", np.ceil(Z)-1)#np.ceil()向上取整
print("方法 4: ", Z.astype(int))
print("方法 5: ", np.trunc(Z))
原始值: [4.17022005e+00 7.20324493e+00 1.14374817e-03 3.02332573e+00
1.46755891e+00 9.23385948e-01 1.86260211e+00 3.45560727e+00
3.96767474e+00 5.38816734e+00]
方法 0: [4. 7. 0. 3. 1. 0. 1. 3. 3. 5.]
方法 1: [4. 7. 0. 3. 1. 0. 1. 3. 3. 5.]
方法 2: [4. 7. 0. 3. 1. 0. 1. 3. 3. 5.]
方法 3: [4. 7. 0. 3. 1. 0. 1. 3. 3. 5.]
方法 4: [4 7 0 3 1 0 1 3 3 5]
方法 5: [4. 7. 0. 3. 1. 0. 1. 3. 3. 5.]
33. 創(chuàng)建一個 5x5 的矩陣,其中每行的數(shù)值范圍從 1 到 5遞增
Z = np.zeros((5, 5))
Z += np.arange(1,6)
Z
array([[1., 2., 3., 4., 5.],
[1., 2., 3., 4., 5.],
[1., 2., 3., 4., 5.],
[1., 2., 3., 4., 5.],
[1., 2., 3., 4., 5.]])
33 創(chuàng)建一個長度為 5 的等間隔一維數(shù)組,其值域范圍從 0 到 1,但是不包括 0 和 1
Z=np.linspace(0,1,6,endpoint=False)[1:]
Z
array([0.16666667, 0.33333333, 0.5 , 0.66666667, 0.83333333])
34. 創(chuàng)建一個長度為10的隨機(jī)一維數(shù)組,并將其按升序或降序排序
np.random.seed(0)
Z = np.random.random(10)
print(Z)
Z.sort()#默認(rèn)升序,改變了Z
Z[::-1]#反轉(zhuǎn)倒序
Z
[0.5488135 0.71518937 0.60276338 0.54488318 0.4236548 0.64589411
0.43758721 0.891773 0.96366276 0.38344152]
array([0.38344152, 0.4236548 , 0.43758721, 0.54488318, 0.5488135 ,
0.60276338, 0.64589411, 0.71518937, 0.891773 , 0.96366276])
-np.sort(-Z)
array([0.96366276, 0.891773 , 0.71518937, 0.64589411, 0.60276338,
0.5488135 , 0.54488318, 0.43758721, 0.4236548 , 0.38344152])
35. 創(chuàng)建一個 3x3 的二維數(shù)組,并將列按升序排序
Z = np.array([[7, 4, 3], [3, 1, 2], [4, 2, 6]])
print("原始數(shù)組: \n", Z)
Z.sort(axis=0)
Z
原始數(shù)組:
[[7 4 3]
[3 1 2]
[4 2 6]]
array([[3, 1, 2],
[4, 2, 3],
[7, 4, 6]])
36. 創(chuàng)建一個長度為 5 的一維數(shù)組,并將其中最大值替換成 0:
Z = np.random.random(5)
print("原數(shù)組: ", Z)
Z[Z.argmax()] = 0
Z
原數(shù)組: [0.79172504 0.52889492 0.56804456 0.92559664 0.07103606]
array([0.79172504, 0.52889492, 0.56804456, 0. , 0.07103606])
37. 打印每個 NumPy 標(biāo)量類型的最小值和最大值
for dtype in [np.int8, np.int32, np.int64]:
print("The minimum value of {}: ".format(dtype), np.iinfo(dtype).min)
print("The maximum value of {}: ".format(dtype), np.iinfo(dtype).max)
for dtype in [np.float32, np.float64]:
print("The minimum value of {}: ".format(dtype), np.finfo(dtype).min)
print("The maximum value of {}: ".format(dtype), np.finfo(dtype).max)
The minimum value of <class 'numpy.int8'>: -128
The maximum value of <class 'numpy.int8'>: 127
The minimum value of <class 'numpy.int32'>: -2147483648
The maximum value of <class 'numpy.int32'>: 2147483647
The minimum value of <class 'numpy.int64'>: -9223372036854775808
The maximum value of <class 'numpy.int64'>: 9223372036854775807
The minimum value of <class 'numpy.float32'>: -3.4028235e+38
The maximum value of <class 'numpy.float32'>: 3.4028235e+38
The minimum value of <class 'numpy.float64'>: -1.7976931348623157e+308
The maximum value of <class 'numpy.float64'>: 1.7976931348623157e+308
38. 將 float32 轉(zhuǎn)換為整型:
Z = np.arange(10, dtype=np.float32)
print(Z)
Z = Z.astype(np.int32, copy=False)
Z
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
39. 將隨機(jī)二維數(shù)組按照第 3 列從上到下進(jìn)行升序排列:
Z = np.random.randint(0, 10, (5, 5))
print("排序前:\n", Z)
#將第三列排序后的索引作為數(shù)組的行索引即完成了按第三列排序,argsort默認(rèn)升序
Z[Z[:, 2].argsort()]
排序前:
[[9 4 3 0 3]
[5 0 2 3 8]
[1 3 3 3 7]
[0 1 9 9 0]
[4 7 3 2 7]]
array([[5, 0, 2, 3, 8],
[9, 4, 3, 0, 3],
[1, 3, 3, 3, 7],
[4, 7, 3, 2, 7],
[0, 1, 9, 9, 0]])
#按第三列降序排序
Z[Z[:, 2].argsort()[::-1]]
array([[0, 1, 9, 9, 0],
[4, 7, 3, 2, 7],
[1, 3, 3, 3, 7],
[9, 4, 3, 0, 3],
[5, 0, 2, 3, 8]])
40. 從隨機(jī)一維數(shù)組中找出距離給定數(shù)值(0.5)最近的數(shù)
np.random.seed(1)
Z = np.random.uniform(0, 1, 20)
print("隨機(jī)數(shù)組: \n", Z)
z = 0.5
m = Z.flat[np.abs(Z - z).argmin()]
m
隨機(jī)數(shù)組:
[4.17022005e-01 7.20324493e-01 1.14374817e-04 3.02332573e-01
1.46755891e-01 9.23385948e-02 1.86260211e-01 3.45560727e-01
3.96767474e-01 5.38816734e-01 4.19194514e-01 6.85219500e-01
2.04452250e-01 8.78117436e-01 2.73875932e-02 6.70467510e-01
4.17304802e-01 5.58689828e-01 1.40386939e-01 1.98101489e-01]
0.538816734003357
Z[np.abs(Z-z).argmin()]
0.538816734003357
41. 將二維數(shù)組的前兩行進(jìn)行順序交換:
A = np.arange(25).reshape(5, 5)
print(A)
A[[0, 1]] = A[[1, 0]]
print(A)
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
[[ 5 6 7 8 9]
[ 0 1 2 3 4]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
42. 找出隨機(jī)一維數(shù)組中出現(xiàn)頻率最高的值:
np.random.seed(1)
Z = np.random.randint(0, 10, 50)
print("隨機(jī)一維數(shù)組:", Z)
np.bincount(Z).argmax()
隨機(jī)一維數(shù)組: [5 8 9 5 0 0 1 7 6 9 2 4 5 2 4 2 4 7 7 9 1 7 0 6 9 9 7 6 9 1 0 1 8 8 3 9 8
7 3 6 5 1 9 3 4 8 1 4 0 3]
9
43. 找出給定一維數(shù)組中非 0 元素的位置索引:
Z = np.nonzero([1, 0, 2, 0, 1, 0, 4, 0])
Z
(array([0, 2, 4, 6], dtype=int32),)
44. 對于給定的 5x5 二維數(shù)組,在其內(nèi)部隨機(jī)放置 p 個值為 1 的數(shù):
p = 3
Z = np.zeros((5, 5))
np.put(Z, np.random.choice(range(5*5), p, replace=False), 1)
Z
array([[0., 1., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 1.],
[0., 1., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
45. 對于隨機(jī)的 3x3 二維數(shù)組,減去數(shù)組每一行的平均值:
X = np.random.rand(3, 3)
print(X)
Y = X - X.mean(axis=1, keepdims=True)
Y
[[0.14672857 0.58930554 0.69975836]
[0.10233443 0.41405599 0.69440016]
[0.41417927 0.04995346 0.53589641]]
array([[-0.33186892, 0.11070805, 0.22116087],
[-0.30126243, 0.01045913, 0.2908033 ],
[ 0.08083622, -0.28338959, 0.20255336]])
46. 獲得二維數(shù)組點(diǎn)積結(jié)果的對角線數(shù)組:
A = np.random.uniform(0, 1, (3, 3))
B = np.random.uniform(0, 1, (3, 3))
print(np.dot(A, B))
# 較慢的方法
np.diag(np.dot(A, B))
[[1.0854637 1.69881997 1.01521735]
[0.86101358 1.30313839 1.04992893]
[0.87724907 1.01397687 0.90035799]]
array([1.0854637 , 1.30313839, 0.90035799])
np.sum(A * B.T, axis=1) # 較快的方法
array([1.0854637 , 1.30313839, 0.90035799])
np.einsum("ij, ji->i", A, B) # 更快的方法
array([1.0854637 , 1.30313839, 0.90035799])
47. 找到隨機(jī)一維數(shù)組中前 p 個最大值:
Z = np.random.randint(1, 100, 100)
print(Z)
p = 5
Z[np.argsort(Z)[-p:]]
[21 33 13 66 95 61 25 83 98 3 93 99 11 55 97 83 87 71 67 72 49 55 16 6
18 43 21 49 23 14 98 54 85 11 97 56 62 57 90 22 97 84 26 15 14 85 44 7
78 57 60 16 25 10 67 72 54 70 37 22 41 78 92 50 48 78 41 79 46 88 17 29
46 68 67 79 47 1 30 64 76 36 54 94 34 3 85 84 49 55 33 29 56 83 32 29
95 75 9 33]
array([97, 97, 98, 98, 99])
48. 計(jì)算隨機(jī)一維數(shù)組中每個元素的 4 次方數(shù)值:
x = np.random.randint(2, 5, 5)
print(x)
np.power(x, 4)
[2 2 3 4 3]
array([ 16, 16, 81, 256, 81], dtype=int32)
49. 對于二維隨機(jī)數(shù)組中各元素,保留其 2 位小數(shù):
Z = np.random.random((5, 5))
print(Z)
np.set_printoptions(precision=2)
Z
[[0.65432377 0.12976961 0.29435948 0.36081475 0.27464515]
[0.07396899 0.15213716 0.16161852 0.9387117 0.3711339 ]
[0.05001809 0.74095556 0.29868024 0.20435813 0.98175664]
[0.89302121 0.75934879 0.65112056 0.0396835 0.81387637]
[0.76257313 0.45528247 0.53182645 0.10933607 0.14603275]]
array([[0.65, 0.13, 0.29, 0.36, 0.27],
[0.07, 0.15, 0.16, 0.94, 0.37],
[0.05, 0.74, 0.3 , 0.2 , 0.98],
[0.89, 0.76, 0.65, 0.04, 0.81],
[0.76, 0.46, 0.53, 0.11, 0.15]])
50. 使用科學(xué)記數(shù)法輸出 NumPy 數(shù)組:
Z = np.random.random([5, 5])
print(Z)
Z/1e3
[[0.51 0.22 0.92 0.46 0.13]
[0.76 0.21 0.07 0.1 0.16]
[0.36 0.1 0.14 0.93 0.58]
[0.84 0.62 0.32 0.73 0.52]
[0.74 0.17 0.69 0.43 0.73]]
array([[5.09e-04, 2.16e-04, 9.16e-04, 4.62e-04, 1.32e-04],
[7.64e-04, 2.13e-04, 7.43e-05, 9.54e-05, 1.62e-04],
[3.56e-04, 9.53e-05, 1.43e-04, 9.31e-04, 5.77e-04],
[8.40e-04, 6.23e-04, 3.25e-04, 7.28e-04, 5.23e-04],
[7.37e-04, 1.65e-04, 6.87e-04, 4.27e-04, 7.29e-04]])
51. 使用 NumPy 找出百分位數(shù)(25%,50%,75%):
a = np.arange(15)
print(a)
np.percentile(a, q=[25, 50, 75])
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
array([ 3.5, 7. , 10.5])
52. 找出數(shù)組中缺失值的總數(shù)及所在位置:
# 生成含缺失值的 2 維數(shù)組
Z = np.random.rand(10, 10)
Z[np.random.randint(10, size=5), np.random.randint(10, size=5)] = np.nan
Z
array([[0.76, nan, 0.93, 0.2 , 0.01, 0.93, 0.29, 0.17, 0.02, 0.45],
[0.81, 0.37, 0.61, 0.03, 0.35, 0.08, 0.69, 0.01, 0.46, 0.96],
[0.33, 0.47, 0.11, 0.5 , 0.89, 0.53, 0.28, 0.35, 0.9 , 0.24],
[0.02, 0.97, 0.43, 0.35, 0.58, 0.13, 0.95, 0.31, 0.95, 0.22],
[0.25, 0.86, 0.24, 0.82, 0.54, 0.19, 0.59, 0.05, 0.02, 0.05],
[0.4 , 0.58, 0.87, 0.79, 0.25, 0.08, 0.16, 0.21, 0.42, 0.35],
[0.7 , 0.7 , 0.07, 0.04, 0.79, 0.9 , 0. , 0.26, 0.47, 0.36],
[0.24, nan, 0.53, 0.13, 0.56, 0.17, 0.42, 0.68, 0.27, 0.01],
[ nan, 0.03, nan, 0.78, 0.52, 0.02, 0.3 , nan, 0.86, 0.19],
[0.08, 0.04, 0.44, 0.02, 0.07, 0.81, 0.64, 0.77, 0.71, 0.24]])
print("缺失值總數(shù): \n", np.isnan(Z).sum())
print("缺失值索引: \n", np.where(np.isnan(Z)))
缺失值總數(shù):
5
缺失值索引:
(array([0, 7, 8, 8, 8], dtype=int32), array([1, 1, 0, 2, 7], dtype=int32))
53. 從隨機(jī)數(shù)組中刪除包含缺失值的行:
# 沿用 52題中的含缺失值的 2 維數(shù)組
Z[np.sum(np.isnan(Z), axis=1) == 0]
array([[0.81, 0.37, 0.61, 0.03, 0.35, 0.08, 0.69, 0.01, 0.46, 0.96],
[0.33, 0.47, 0.11, 0.5 , 0.89, 0.53, 0.28, 0.35, 0.9 , 0.24],
[0.02, 0.97, 0.43, 0.35, 0.58, 0.13, 0.95, 0.31, 0.95, 0.22],
[0.25, 0.86, 0.24, 0.82, 0.54, 0.19, 0.59, 0.05, 0.02, 0.05],
[0.4 , 0.58, 0.87, 0.79, 0.25, 0.08, 0.16, 0.21, 0.42, 0.35],
[0.7 , 0.7 , 0.07, 0.04, 0.79, 0.9 , 0. , 0.26, 0.47, 0.36],
[0.08, 0.04, 0.44, 0.02, 0.07, 0.81, 0.64, 0.77, 0.71, 0.24]])
54. 統(tǒng)計(jì)隨機(jī)數(shù)組中的各元素的數(shù)量:
Z = np.random.randint(0, 100, 25).reshape(5, 5)
print(Z)
np.unique(Z, return_counts=True) # 返回值中,第 2 個數(shù)組對應(yīng)第 1 個數(shù)組
[[10 28 75 5 81]
[ 5 42 86 52 57]
[56 78 87 81 10]
[72 48 19 12 25]
[77 16 4 88 27]]
(array([ 4, 5, 10, 12, 16, 19, 25, 27, 28, 42, 48, 52, 56, 57, 72, 75, 77,
78, 81, 86, 87, 88]),
array([1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1]))
55. 將數(shù)組中各元素按指定分類轉(zhuǎn)換為文本值:
# 指定類別1 → 汽車 2 → 公交車 3 → 火車
Z = np.random.randint(1, 4, 10)
print(Z)
label_map = {1: "汽車", 2: "公交車", 3: "火車"}
[label_map[x] for x in Z]
[3 1 3 1 3 1 1 1 2 1]
['火車', '汽車', '火車', '汽車', '火車', '汽車', '汽車', '汽車', '公交車', '汽車']
56. 將多個 1 維數(shù)組拼合為單個 Ndarray:
Z1 = np.arange(3)
Z2 = np.arange(3, 7)
Z3 = np.arange(7, 10)
Z = np.array([Z1, Z2, Z3])
print(Z)
np.concatenate(Z)
[array([0, 1, 2]) array([3, 4, 5, 6]) array([7, 8, 9])]
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
57. 打印各元素在數(shù)組中升序排列的索引:
a = np.random.randint(100, size=10)
print('Array: ', a)
a.argsort()
Array: [74 12 18 30 59 5 16 95 96 60]
array([5, 1, 6, 2, 3, 4, 9, 0, 7, 8], dtype=int32)
58.得到二維隨機(jī)數(shù)組各行的最小值(區(qū)別上面的方法):
Z = np.random.randint(1, 100, [5, 5])
print(Z)
np.apply_along_axis(np.min, arr=Z, axis=1)
[[44 32 45 25 63]
[80 22 20 78 34]
[ 5 40 68 35 35]
[43 79 83 39 49]
[82 6 92 9 41]]
array([25, 20, 5, 39, 6])
59. 計(jì)算兩個數(shù)組之間的歐氏距離:
a = np.array([1, 2])
b = np.array([7, 8])
# 數(shù)學(xué)計(jì)算方法
print(np.sqrt(np.sum((a-b)**2)))
# NumPy 計(jì)算
np.linalg.norm(b-a)
8.48528137423857
8.48528137423857
60.打印復(fù)數(shù)的實(shí)部和虛部:
a = np.array([1 + 2j, 3 + 4j, 5 + 6j])
print("實(shí)部:", a.real)
print("虛部:", a.imag)
實(shí)部: [1. 3. 5.]
虛部: [2. 4. 6.]
61. 求解給出矩陣的逆矩陣并驗(yàn)證:
matrix = np.array([[1., 2.], [3., 4.]])
inverse_matrix = np.linalg.inv(matrix)
# 驗(yàn)證原矩陣和逆矩陣的點(diǎn)積是否為單位矩陣
assert np.allclose(np.dot(matrix, inverse_matrix), np.eye(2))
inverse_matrix
array([[-2. , 1. ],
[ 1.5, -0.5]])
62. 使用 Z-Score 標(biāo)準(zhǔn)化算法對數(shù)據(jù)進(jìn)行標(biāo)準(zhǔn)化處理:
Z-Score 標(biāo)準(zhǔn)化公式:
Z=X?mean(X)/sd(X)
# 根據(jù)公式定義函數(shù)
def zscore(x, axis=None):
xmean = x.mean(axis=axis, keepdims=True)
xstd = np.std(x, axis=axis, keepdims=True)
zscore = (x-xmean)/xstd
return zscore
# 生成隨機(jī)數(shù)據(jù)
Z = np.random.randint(10, size=(5, 5))
print(Z)
zscore(Z)
[[5 5 7 5 9]
[1 3 9 3 3]
[3 6 1 3 0]
[5 0 5 2 7]
[6 4 0 2 4]]
array([[ 0.43, 0.43, 1.22, 0.43, 2.01],
[-1.15, -0.36, 2.01, -0.36, -0.36],
[-0.36, 0.82, -1.15, -0.36, -1.55],
[ 0.43, -1.55, 0.43, -0.76, 1.22],
[ 0.82, 0.03, -1.55, -0.76, 0.03]])
63. 使用 Min-Max 標(biāo)準(zhǔn)化算法對數(shù)據(jù)進(jìn)行標(biāo)準(zhǔn)化處理:
Min-Max 標(biāo)準(zhǔn)化公式:
Y=Z?min(Z)/max(Z)?min(Z)
# 根據(jù)公式定義函數(shù)
def min_max(x, axis=None):
min = x.min(axis=axis, keepdims=True)
max = x.max(axis=axis, keepdims=True)
result = (x-min)/(max-min)
return result
# 生成隨機(jī)數(shù)據(jù)
Z = np.random.randint(10, size=(5, 5))
print(Z)
min_max(Z)
[[8 7 6 7 7]
[1 7 7 3 8]
[3 0 6 3 0]
[6 5 9 6 4]
[6 6 2 2 4]]
array([[0.89, 0.78, 0.67, 0.78, 0.78],
[0.11, 0.78, 0.78, 0.33, 0.89],
[0.33, 0. , 0.67, 0.33, 0. ],
[0.67, 0.56, 1. , 0.67, 0.44],
[0.67, 0.67, 0.22, 0.22, 0.44]])
64. 使用 L2 范數(shù)對數(shù)據(jù)進(jìn)行標(biāo)準(zhǔn)化處理:
L2 范數(shù):平方和求開方
# 根據(jù)公式定義函數(shù)
def l2_normalize(v, axis=-1, order=2):
l2 = np.linalg.norm(v, ord=order, axis=axis, keepdims=True)
l2[l2 == 0] = 1
return v/l2
# 生成隨機(jī)數(shù)據(jù)
Z = np.random.randint(10, size=(5, 5))
print(Z)
l2_normalize(Z)
[[1 2 3 9 3]
[6 7 0 3 3]
[6 8 6 5 1]
[3 2 6 3 6]
[7 2 8 0 1]]
array([[0.1 , 0.2 , 0.29, 0.88, 0.29],
[0.59, 0.69, 0. , 0.3 , 0.3 ],
[0.47, 0.63, 0.47, 0.39, 0.08],
[0.31, 0.21, 0.62, 0.31, 0.62],
[0.64, 0.18, 0.74, 0. , 0.09]])
65. 使用 NumPy 計(jì)算變量直接的相關(guān)性系數(shù):
相關(guān)性系數(shù)取值區(qū)間為[?1,1] ,絕對值越接近1,相關(guān)性越強(qiáng),符號表明正負(fù)相關(guān)。
Z = np.array([
[1, 2, 1, 9, 10, 3, 2, 6, 7], # 特征 A
[2, 1, 8, 3, 7, 5, 10, 7, 2], # 特征 B
[2, 1, 1, 8, 9, 4, 3, 5, 7]]) # 特征 C
np.corrcoef(Z)
array([[ 1. , -0.06, 0.97],
[-0.06, 1. , -0.01],
[ 0.97, -0.01, 1. ]])
66. 使用 NumPy 計(jì)算矩陣的特征值和特征向量:
M = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
w, v = np.linalg.eig(M)
# w 對應(yīng)特征值,v 對應(yīng)特征向量
w, v
(array([ 1.61e+01, -1.12e+00, -1.30e-15]), matrix([[-0.23, -0.79, 0.41],
[-0.53, -0.09, -0.82],
[-0.82, 0.61, 0.41]]))
我們可以通過 P′AP=MP′AP=M 公式反算,驗(yàn)證是否能得到原矩陣。
v * np.diag(w) * np.linalg.inv(v)
matrix([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]])
67. 使用 NumPy 計(jì)算 Ndarray 兩相鄰元素差值:
Z = np.random.randint(1, 10, 10)
print(Z)
# 計(jì)算 Z 兩相鄰元素差值
print(np.diff(Z, n=1))
# 重復(fù)計(jì)算 2 次
print(np.diff(Z, n=2))
# 重復(fù)計(jì)算 3 次
print(np.diff(Z, n=3))
[9 7 1 1 2 3 8 8 5 5]
[-2 -6 0 1 1 5 0 -3 0]
[-4 6 1 0 4 -5 -3 3]
[10 -5 -1 4 -9 2 6]
68. 使用 NumPy 將 Ndarray 相鄰元素依次累加:
Z = np.random.randint(1, 10, 10)
print(Z)
"""
[第一個元素, 第一個元素 + 第二個元素, 第一個元素 + 第二個元素 + 第三個元素, ...]
"""
np.cumsum(Z)
[1 2 1 9 6 7 3 6 5 4]
array([ 1, 3, 4, 13, 19, 26, 29, 35, 40, 44], dtype=int32)
69. 使用 NumPy 打印九九乘法表:
np.fromfunction(lambda i, j: (i + 1) * (j + 1), (9, 9))
array([[ 1., 2., 3., 4., 5., 6., 7., 8., 9.],
[ 2., 4., 6., 8., 10., 12., 14., 16., 18.],
[ 3., 6., 9., 12., 15., 18., 21., 24., 27.],
[ 4., 8., 12., 16., 20., 24., 28., 32., 36.],
[ 5., 10., 15., 20., 25., 30., 35., 40., 45.],
[ 6., 12., 18., 24., 30., 36., 42., 48., 54.],
[ 7., 14., 21., 28., 35., 42., 49., 56., 63.],
[ 8., 16., 24., 32., 40., 48., 56., 64., 72.],
[ 9., 18., 27., 36., 45., 54., 63., 72., 81.]])
70. 使用 NumPy 將Numpy LOGO 轉(zhuǎn)換為 Ndarray 數(shù)組:
from io import BytesIO
from PIL import Image
import PIL
import requests
# 通過鏈接下載圖像
URL = 'https://numpy.org/_static/numpy_logo.png'
response=requests.get(URL)
# 將內(nèi)容讀取為圖像
I = Image.open(BytesIO(response.content))
# 將圖像轉(zhuǎn)換為 Ndarray
numpy = np.asarray(I)
numpy.shape
(61, 180, 3)
# 將轉(zhuǎn)換后的 Ndarray 重新繪制成圖像
from matplotlib import pyplot as plt
%matplotlib inline
plt.imshow(numpy)
plt.show()
