主頁 > 後端開發 > 學習NumPy全套代碼【超詳細】基本操作、資料型別、陣列運算、復制和試圖、索引、切片和迭代、形狀操作、通用函式、線性代數

學習NumPy全套代碼【超詳細】基本操作、資料型別、陣列運算、復制和試圖、索引、切片和迭代、形狀操作、通用函式、線性代數

2021-11-08 10:11:32 後端開發

大家好,我又來給大家分享新知識了,最近幾篇博客(文末有鏈接)都致力于將以前的學習資源整理成博客的形式分享給大家,真心干貨滿滿,希望能給大家帶來識訓,

那么本篇博客將會給出大家平時使用NumPy的時候經常需要用到的功能代碼,同時也會給出運行結果,以幫助大家更進一步的理解,

另外,我也以注釋的形式更進一步的補充說明代碼的功能及其作用,需要本篇博文中用到的檔案檔案以及代碼的朋友,也可以三連支持一下,并評論留下你的郵箱,我會在看到后的第一時間發送給你,

當然啦,你也可以把本篇博文當作一本小小的NumPy書籍,當需要用到pandas哪些知識的時候,Ctrl+F就可以搜索到啦,現在不看的話就先收藏著,

目錄

  • 一、基本操作
    • 1.1 陣列創建
    • 1.2 查看陣列屬性
    • 1.3 檔案讀寫
  • 二、資料型別
  • 三、陣列運算
    • 3.1 基本運算
    • 3.2 邏輯運算
    • 3.3 陣列與標量計算
    • 3.4 -= += *=直接改變原陣列
  • 四、復制和視圖
    • 4.1 完全沒有復制
    • 4.2 視圖、查看或者淺拷貝
    • 4.3 深拷貝
  • 五、索引、切片和迭代
    • 5.1 基本索引和切片
    • 5.2 花式索引和索引技巧
  • 六、形狀操作
    • 6.1 陣列變形
    • 6.2 陣列轉置
    • 6.3 資料堆疊合并
    • 6.4 陣列拆分
  • 七、廣播機制
  • 八、通用函式
    • 8.1 元素級數字級別的方法
    • 8.2 where函式
    • 8.3 排序
    • 8.4 集合操作
    • 8.5 數學和統計函式
  • 九、線性代數
  • 結束語

一、基本操作

1.1 陣列創建

import numpy as np # Shift + Enter
# 創建可以將Python,中list串列轉換成NumPy陣列
l = [1,2,3,4,5]

# NumPy陣列
nd1 = np.array(l) # 輸入一部分arr + tab(命令中自動補全,按鍵) 代碼提示,自動補全
print(nd1)
display(nd1) # 顯示
[1 2 3 4 5]



array([1, 2, 3, 4, 5])
nd2 = np.zeros(shape = (3,4),dtype = np.int16) # shift + tab提示方法的屬性,使用
nd2
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]], dtype=int16)
nd3 = np.ones(shape = (3,5),dtype=np.float32)
nd3 # juppyter中執行程式,代碼,最后一行,默認就是輸出
array([[1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]], dtype=float32)
# 三維陣列
nd4 = np.full(shape = (3,4,5),fill_value=3.1415926) # 生成任意指定的陣列
nd4
array([[[3.1415926, 3.1415926, 3.1415926, 3.1415926, 3.1415926],
        [3.1415926, 3.1415926, 3.1415926, 3.1415926, 3.1415926],
        [3.1415926, 3.1415926, 3.1415926, 3.1415926, 3.1415926],
        [3.1415926, 3.1415926, 3.1415926, 3.1415926, 3.1415926]],

       [[3.1415926, 3.1415926, 3.1415926, 3.1415926, 3.1415926],
        [3.1415926, 3.1415926, 3.1415926, 3.1415926, 3.1415926],
        [3.1415926, 3.1415926, 3.1415926, 3.1415926, 3.1415926],
        [3.1415926, 3.1415926, 3.1415926, 3.1415926, 3.1415926]],

       [[3.1415926, 3.1415926, 3.1415926, 3.1415926, 3.1415926],
        [3.1415926, 3.1415926, 3.1415926, 3.1415926, 3.1415926],
        [3.1415926, 3.1415926, 3.1415926, 3.1415926, 3.1415926],
        [3.1415926, 3.1415926, 3.1415926, 3.1415926, 3.1415926]]])
nd5 = np.random.randint(0,100,size = 20) # 從0,到100,生成亂數字,int,整數
nd5
array([26, 97, 32, 88, 28, 65, 77, 74, 68, 97, 32, 35, 46, 55, 33, 83, 63,
        6, 77,  5])
nd6 = np.random.rand(3,5) # 生成0~1之間亂數
nd6
array([[0.64501117, 0.58522154, 0.90132264, 0.99409845, 0.63923959],
       [0.2164321 , 0.53874694, 0.54988461, 0.82581533, 0.42652412],
       [0.01025381, 0.49834132, 0.71353756, 0.44433708, 0.05175048]])
nd7 = np.random.randn(3,5) # 正態分布,平均值是0,標準差是1
display(nd7)
array([[-1.34974864, -0.35255807, -0.06337357, -0.39990286,  0.18276669],
       [ 0.42686337, -0.29675634, -0.66351388,  0.15499455,  0.22191029],
       [-2.24510816, -0.25372978,  0.61602861, -0.53877681,  1.8443575 ]])
nd8 = np.random.normal(loc = 175,scale = 10,size = (3,5)) # 正態分布,平均值是175,標準差是10
print(nd8)
[[154.35099611 188.63428445 178.86129064 173.99374674 173.92688007]
 [173.48768953 185.57252565 172.63843251 192.40089968 177.04776165]
 [166.25486758 198.20977267 162.28102209 167.1159521  183.41324182]]
nd9 = np.arange(1,100,step = 10) # 等引數列,左閉右開,100取不到
nd9
array([ 1, 11, 21, 31, 41, 51, 61, 71, 81, 91])
nd10 = np.linspace(1,100,num = 19) # 等引數列,左閉右閉,num表示生成等引數列長度
nd10
array([  1. ,   6.5,  12. ,  17.5,  23. ,  28.5,  34. ,  39.5,  45. ,
        50.5,  56. ,  61.5,  67. ,  72.5,  78. ,  83.5,  89. ,  94.5,
       100. ])

1.2 查看陣列屬性

import numpy as np

nd = np.random.randn(5,3)
nd
array([[ 0.72059556, -1.95187973, -0.56373137],
       [-1.73917205, -1.16500837,  1.42147895],
       [ 0.38178684, -1.44311435, -0.47301186],
       [-1.02896549,  0.05223197,  0.05234227],
       [ 0.21264316, -1.0635056 , -0.98622601]])
# 查看陣列形狀,回傳了形狀 shape = (5,3)
nd.shape
(5, 3)
nd.dtype # 告訴陣列的資料型別 float64 位,一位占一個0或者一個1
dtype('float64')
nd.size # 尺寸,陣列可以是多維的,請問,里面共有多少資料 3*5 = 15
15
nd.ndim # 陣列維度 
2
nd.itemsize # 條目 尺寸長度 8 位元組
# 資料型別是float64 64位 -----> 1個位元組8位-----> 64/8 = 8 位元組
8

1.3 檔案讀寫

nd1 = np.random.randint(0,100,size = (3,5))
nd2 = np.random.randn(3,5)
display(nd1,nd2)
array([[17,  9, 81, 22, 35],
       [33,  3, 76, 56, 39],
       [51,  7, 98, 68, 76]])



array([[-1.00157588, -1.42826357, -0.0595288 ,  1.52754491, -0.36709515],
       [-1.27106787,  0.10364645,  0.32066376, -1.66321598, -1.25959691],
       [-1.71740637, -0.25518009, -0.81794158,  0.76914636,  1.14322894]])
np.save('./data',nd1) # 把一個資料存到檔案中
np.load('./data.npy') # 默認添加npy后綴
array([[17,  9, 81, 22, 35],
       [33,  3, 76, 56, 39],
       [51,  7, 98, 68, 76]])
# 多個資料存到一個檔案中
np.savez('./data.npz',a = nd1,abc = nd2) # 保存資料是起名:a,abc,稱為key,自己命名
data = np.load('./data.npz')
data
<numpy.lib.npyio.NpzFile at 0x2352497f7c8>
data['a'] # 單引號
array([[17,  9, 81, 22, 35],
       [33,  3, 76, 56, 39],
       [51,  7, 98, 68, 76]])
data['abc']
array([[-1.00157588, -1.42826357, -0.0595288 ,  1.52754491, -0.36709515],
       [-1.27106787,  0.10364645,  0.32066376, -1.66321598, -1.25959691],
       [-1.71740637, -0.25518009, -0.81794158,  0.76914636,  1.14322894]])
# data['www'] # 沒有保存,無法獲取
np.savez_compressed('./data2.npz',x = nd1,y = nd2)
np.load('./data2.npz')['x']
array([[0, 4, 9, 0, 8],
       [6, 2, 5, 1, 1],
       [7, 5, 2, 4, 3]])
np.savetxt(fname = './data.txt',# 檔案名
           X = nd1, # 資料
           fmt='%0.2f', # 格式
           delimiter=',')# 分隔符
np.savetxt(fname = './data.cvs',# 檔案名
           X = nd1, # 資料
           fmt='%d', # 格式
           delimiter=';')# 分隔符
np.loadtxt('./data.cvs',delimiter=';')
array([[0., 4., 9., 0., 8.],
       [6., 2., 5., 1., 1.],
       [7., 5., 2., 4., 3.]])
np.loadtxt('./data.txt',delimiter=',')
array([[0., 4., 9., 0., 8.],
       [6., 2., 5., 1., 1.],
       [7., 5., 2., 4., 3.]])

二、資料型別

# int8,int16,int32,int64,uint8無符號
# float16,float32,float64
# str字串型別
# int8 表示 2**8個數字 256個 -128 ~ 127 有符號
# uint8 表示256個數字,無符號,表明只有正數:0 ~ 255

np.array([2,4,7],dtype = np.int8)
array([2, 4, 7], dtype=int8)
np.array([-3,-7,255,108,0,256],dtype = np.uint8)
array([253, 249, 255, 108,   0,   0], dtype=uint8)
np.random.randint(0,100,size = 10,dtype = 'int64')
array([ 8, 36, 88, 80, 20, 52, 83, 42, 18,  1], dtype=int64)
nd = np.random.rand(10,2)
nd
array([[0.91420288, 0.83364378],
       [0.88974876, 0.33297581],
       [0.40118288, 0.07479842],
       [0.16937616, 0.26712123],
       [0.94525666, 0.34948455],
       [0.96704048, 0.61851364],
       [0.90099123, 0.3941368 ],
       [0.58999302, 0.40133028],
       [0.95706455, 0.53783821],
       [0.19142784, 0.38579803]])
nd.dtype
dtype('float64')
np.asarray(nd,dtype = 'float16')
array([[0.914  , 0.8335 ],
       [0.8896 , 0.333  ],
       [0.4011 , 0.07477],
       [0.1694 , 0.267  ],
       [0.9453 , 0.3494 ],
       [0.967  , 0.6187 ],
       [0.901  , 0.394  ],
       [0.59   , 0.4014 ],
       [0.957  , 0.5376 ],
       [0.1914 , 0.3857 ]], dtype=float16)
nd.astype(dtype = np.float16)
array([[0.914  , 0.8335 ],
       [0.8896 , 0.333  ],
       [0.4011 , 0.07477],
       [0.1694 , 0.267  ],
       [0.9453 , 0.3494 ],
       [0.967  , 0.6187 ],
       [0.901  , 0.394  ],
       [0.59   , 0.4014 ],
       [0.957  , 0.5376 ],
       [0.1914 , 0.3857 ]], dtype=float16)
nd = np.random.randn(1000,3) # 默認資料型別是float64
np.save('./data1',nd)
np.save('./data2',nd.astype('float16'))
nd2 = np.array(list('abcdefghi'))
nd2
array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], dtype='<U1')
nd2.dtype
dtype('<U1')

三、陣列運算

3.1 基本運算

# 加減乘除指數冪運算
nd1 = np.random.randint(0,10,size = 5)
nd2 = np.random.randint(0,10,size = 5)
display(nd1,nd2)
array([7, 9, 4, 6, 7])



array([0, 4, 6, 6, 0])
nd3 = nd1 - nd2 # 回傳一個新物件,原來的陣列,內容不變!
nd3 # nd3陣列操作后,接收的物件
array([ 7,  5, -2,  0,  7])
nd1 * nd2 # 乘法
array([ 0, 36, 24, 36,  0])
nd1 / nd2 # 除法
d:\python\lib\site-packages\ipykernel_launcher.py:1: RuntimeWarning: divide by zero encountered in true_divide
  """Entry point for launching an IPython kernel.





array([       inf, 2.25      , 0.66666667, 1.        ,        inf])
nd1**nd2 # 冪運算
array([    1,  6561,  4096, 46656,     1], dtype=int32)
2**3
8
np.power(2,3) # 表示2的3次冪
8
np.power(nd1,nd2) # 表示nd1的nd2次冪,對應位置,進行計算
array([    1,  6561,  4096, 46656,     1], dtype=int32)
np.log(100) # 底數是自然底數e 2.718
4.605170185988092
np.log10(1000) # 對數運算回傳結果是:3
3.0
np.log2(1024) # 回傳結果就是:10
10.0

3.2 邏輯運算

display(nd1,nd2)
array([7, 9, 4, 6, 7])



array([0, 4, 6, 6, 0])
nd1 > nd2
array([ True,  True, False, False,  True])
nd1 < nd2
array([False, False,  True, False, False])
nd1 >= nd2 # 表示nd1陣列中的資料,是否大于等于nd2中的對應位置的資料,如果大于等于,放回True
array([ True,  True, False,  True,  True])
nd1 == nd2 # 兩個等號表示邏輯判斷,問,是否相等
array([False, False, False,  True, False])

3.3 陣列與標量計算

nd1
array([7, 9, 4, 6, 7])
# 數字3,4,5……都是標量
nd1 + 10 # 所有的位置都加了10,廣播
array([17, 19, 14, 16, 17])
nd1 - 1024
array([-1017, -1015, -1020, -1018, -1017])
nd1 * 256
array([1792, 2304, 1024, 1536, 1792])
nd1 / 1024
array([0.00683594, 0.00878906, 0.00390625, 0.00585938, 0.00683594])
# 陣列可以做分母,注意不能有0
1/nd1
array([0.14285714, 0.11111111, 0.25      , 0.16666667, 0.14285714])
1/np.array([1,3,0,5]) # 0不能作為分母計算結果:inf 
d:\python\lib\site-packages\ipykernel_launcher.py:1: RuntimeWarning: divide by zero encountered in true_divide
  """Entry point for launching an IPython kernel.





array([1.        , 0.33333333,        inf, 0.2       ])

3.4 -= += *=直接改變原陣列

display(nd1,nd2) # 沒變化
array([7, 9, 4, 6, 7])



array([0, 4, 6, 6, 0])
nd1 -= 100 # 沒有列印輸出,說明,改變了原來的陣列
nd1
array([-93, -91, -96, -94, -93])
nd2 +=100
nd2
array([100, 104, 106, 106, 100])
nd1 *= 3
nd1
array([-279, -273, -288, -282, -279])
# nd1 /= 10 陣列不支持 /=

四、復制和視圖

4.1 完全沒有復制

a = np.random.randint(0,10,size = 5)
b = a # 賦值操作
display(a,b)
array([7, 9, 3, 2, 9])



array([7, 9, 3, 2, 9])
a is b # 回傳True說明,賦值操作,a和b一回事
True
a[0] = 1024 # 改變a那么b也發生了變化
display(a,b)
array([1024,    9,    3,    2,    9])



array([1024,    9,    3,    2,    9])

4.2 視圖、查看或者淺拷貝

a = np.random.randint(0,100,size = 5)
b = a.view() # 視圖,查看,淺拷貝
display(a,b)
array([69, 16, 91,  6, 96])



array([69, 16, 91,  6, 96])
a is b # 說明a和b不一樣
False
a.flags.owndata # a陣列資料是自己的
True
b.flags.owndata # b是淺拷貝a的資料,也就是b并不擁有自己的資料
False
a[0] = 1024
b[1] = 2048 # 無論修改誰,最終結果兩個陣列都發生了變化
display(a,b)
array([1024, 2048,   91,    6,   96])



array([1024, 2048,   91,    6,   96])

4.3 深拷貝

a = np.random.randint(-100,0,size = 10)
b = a.copy() # 深拷貝,此時,a和b沒有關系了
display(a,b)
array([-99,  -5, -16,  -5, -11, -72, -57, -69, -66, -96])



array([-99,  -5, -16,  -5, -11, -72, -57, -69, -66, -96])
display(a is b)
display(a.flags.owndata)
display(b.flags.owndata) # b 物件擁有自己的資料
False



True



True
a[0] = 1024
b[2] = 2048 # 井水不犯河水
display(a,b)
array([1024,   -5,  -16,   -5,  -11,  -72,  -57,  -69,  -66,  -96])



array([ -99,   -5, 2048,   -5,  -11,  -72,  -57,  -69,  -66,  -96])
a = np.arange(1e8) # 0 ~ 1億,資料量非常多的
a
array([0.0000000e+00, 1.0000000e+00, 2.0000000e+00, ..., 9.9999997e+07,
       9.9999998e+07, 9.9999999e+07])
b = a[[1,3,5,7,9,99]].copy() # 取出一部分資料,原來的陣列,沒有了,但是占記憶體特別大
del a # 洗掉原來的陣列,記憶體優化
b
array([ 1.,  3.,  5.,  7.,  9., 99.])

五、索引、切片和迭代

5.1 基本索引和切片

a = np.random.randint(0,30,size = 10)
a
array([28, 19,  9, 26, 28,  4, 14, 24,  8,  3])
a[3] # 取一個
a[[1,3,5]] # 取多個 
array([19, 26,  4])
a[0:3] # 左閉右開
array([28, 19,  9])
a[:3] # 如果冒號前面不寫,默認從0開始
array([28, 19,  9])
a[5:9] # 從某個索引開始切片
array([ 4, 14, 24,  8])
a[5:] # 冒號后面不寫內容,那么默認就是到左后
array([ 4, 14, 24,  8,  3])
a[::2] # 兩個中取一個
array([28,  9, 28, 14,  8])
a[3::3] # 從索引3開始,每三個數中,取一個
array([26, 14,  3])
a[::-1] # 倒著數,陣列進行了顛倒
array([ 3,  8, 24, 14,  4, 28, 26,  9, 19, 28])
a
array([28, 19,  9, 26, 28,  4, 14, 24,  8,  3])
a[::-2] # 顛倒,兩個中取一個
array([ 3, 24,  4, 26, 19])
a[5::-3]
array([4, 9])
a[1:7:2] # 從索引1開始到7結束,每兩個中取一個
array([19, 26,  4])
b = np.random.randint(0,30,size = (10,10))
b # 二維陣列,多維資料索引和切片和上面的規律一樣
array([[25, 23, 13, 28, 17, 13,  8, 16, 25,  3],
       [20,  7,  6, 26, 26, 13, 24,  0, 20, 18],
       [ 1, 24, 10, 25, 24, 21, 16,  4, 26, 29],
       [12,  0, 18, 20,  9, 16, 14, 19, 19, 20],
       [28, 18, 29,  7,  7, 15,  5, 13, 13,  7],
       [28, 28, 25, 13,  7,  8,  5, 16,  8,  2],
       [27,  9,  2, 25, 14,  7, 26,  5, 14, 11],
       [ 6, 14, 10, 20, 24, 28, 10,  0, 24, 12],
       [ 8, 21, 22, 21, 24,  6, 25, 21, 12, 26],
       [ 0, 19,  8,  5, 20,  1,  3,  3, 15, 27]])
b[1]
array([20,  7,  6, 26, 26, 13, 24,  0, 20, 18])
b[[0,3,5]]
array([[25, 23, 13, 28, 17, 13,  8, 16, 25,  3],
       [12,  0, 18, 20,  9, 16, 14, 19, 19, 20],
       [28, 28, 25, 13,  7,  8,  5, 16,  8,  2]])
b[1,6]
24
b[3,[2,5,6]] # 多維陣列,不怕,我們可以用逗號,分割
array([18, 16, 14])
b[2:7,1::3] # 行:從2到索引7,列:從1開始,每3個中取一個數字
array([[24, 24,  4],
       [ 0,  9, 19],
       [18,  7, 13],
       [28,  7, 16],
       [ 9, 14,  5]])
b[-1,-1] # 給-1表示倒著數
27
b[-2,[-2,-3,-4]]
array([12, 21, 25])

5.2 花式索引和索引技巧

a = np.arange(20)
a
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19])
b = a[3:7] # 切片時,回傳的資料,不是深拷貝
b
array([3, 4, 5, 6])
b[0] = 1024
display(a,b)
array([   0,    1,    2, 1024,    4,    5,    6,    7,    8,    9,   10,
         11,   12,   13,   14,   15,   16,   17,   18,   19])



array([1024,    4,    5,    6])
a = np.arange(20)
# 花式索引回傳的深拷貝的資料
b = a[[3,4,5,6]] # 花式索引:就是在索引是,給了一個陣列
display(a,b)
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19])



array([3, 4, 5, 6])
b[0] = 1024
display(a,b)
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19])



array([1024,    4,    5,    6])
a = np.random.randint(0,151,size = (100,3)) # 100名學生,參加了3門考試:Python、Math、En
a
array([[100, 128, 122],
       [110,   1,   6],
       [120, 100, 108],
       [ 57, 112, 145],
       [ 46, 121, 130],
       [141,  20,  25],
       [  7,  98,  15],
       [141, 145, 121],
       [  1,  29, 117],
       [ 94,  62,  46],
       [ 35, 135, 101],
       [ 96,  38, 137],
       [ 97, 114,  60],
       [121, 113,  38],
       [  4,  85, 107],
       [ 13,  79,  12],
       [129,  92, 150],
       [ 54,  38,  34],
       [109,  55,  88],
       [  1,  52,  23],
       [ 16,  80, 146],
       [122,  72, 126],
       [ 39,  76,  52],
       [144,  68,  69],
       [121, 141, 147],
       [141,  71, 110],
       [100,  40, 108],
       [ 91, 121,  65],
       [  3,  44, 105],
       [ 79,  61,  75],
       [117, 146,  88],
       [  3,   2,  71],
       [ 78,  24,  86],
       [125,  62,  93],
       [ 53,  88, 132],
       [ 96,  75,  36],
       [102, 119,  97],
       [ 24,  48,  78],
       [104,  21, 150],
       [  8,  34,  30],
       [108,  56,  58],
       [ 22, 144, 100],
       [ 53, 115,  94],
       [ 52, 104,   9],
       [ 59,   2,   4],
       [ 85,  48, 138],
       [119,  21,  73],
       [  9,  31,  77],
       [ 21,   3, 132],
       [ 43, 113,  39],
       [ 51,   5, 134],
       [ 37,  97, 123],
       [  0,  92,  73],
       [ 37,  86,  13],
       [ 48,  78, 128],
       [ 74,  56,  48],
       [138, 105,  68],
       [129, 129, 103],
       [ 48,  42,  14],
       [ 50, 102, 123],
       [  6,  97,  16],
       [ 22,  88, 122],
       [ 98,  23, 137],
       [ 95,  74,  20],
       [ 20, 111, 132],
       [ 67,   9,  28],
       [ 74,   1,  79],
       [ 62,   8,  27],
       [ 24,  12,  22],
       [ 58, 111, 130],
       [ 29,  23,  28],
       [ 10,  30,  38],
       [113,  62, 122],
       [ 70, 141,  97],
       [137, 106,  53],
       [ 76,  91, 101],
       [128,  22, 101],
       [134,  75, 100],
       [114,  92,  79],
       [103,  20, 145],
       [105,  26,  51],
       [ 34,  51,  18],
       [117, 115,  31],
       [  7, 119,  75],
       [ 23,  74, 149],
       [ 56,  15,  11],
       [143,  73, 148],
       [ 11,  22,  26],
       [ 18, 113, 120],
       [ 37, 150,  21],
       [115,  89,  13],
       [134, 108,  98],
       [115,  58,   4],
       [114,  58,  29],
       [ 26, 135,  10],
       [ 82, 147, 147],
       [ 56,  13,  39],
       [ 21, 125, 134],
       [120,  71,  32],
       [143,  46, 124]])
cond = a >= 120 # 邏輯運算
# 根據條件,篩選資料,只要大于120,回傳,一門大于120,就會回傳這一門
a[cond]
array([128, 122, 120, 145, 121, 130, 141, 141, 145, 121, 135, 137, 121,
       129, 150, 146, 122, 126, 144, 121, 141, 147, 141, 121, 146, 125,
       132, 150, 144, 138, 132, 134, 123, 128, 138, 129, 129, 123, 122,
       137, 132, 130, 122, 141, 137, 128, 134, 145, 149, 143, 148, 120,
       150, 134, 135, 147, 147, 125, 134, 120, 143, 124])
# boolean True = 1;False = 0
# 三門科目的條件進行相乘
# 三個科目都是 大于120的同學
cond2 = cond[:,0]*cond[:,1]*cond[:,2]
a[cond2]
array([[141, 145, 121],
       [121, 141, 147]])
# 大于等于120,小于等于30找到
cond1 = a >=120
cond2 = a <= 30
a[cond2[:,0]*cond2[:,1]*cond2[:,2]]
array([[24, 12, 22],
       [29, 23, 28],
       [11, 22, 26]])

六、形狀操作

6.1 陣列變形

a = np.random.randint(0,10,size = (3,5))
a
array([[0, 2, 3, 7, 1],
       [2, 1, 9, 3, 0],
       [3, 3, 8, 7, 1]])
a.reshape(5,3) # 只是改變形狀
array([[0, 2, 3],
       [7, 1, 2],
       [1, 9, 3],
       [0, 3, 3],
       [8, 7, 1]])
a.reshape(15,1,1)
array([[[0]],

       [[2]],

       [[3]],

       [[7]],

       [[1]],

       [[2]],

       [[1]],

       [[9]],

       [[3]],

       [[0]],

       [[3]],

       [[3]],

       [[8]],

       [[7]],

       [[1]]])
a.reshape(-1,3) # -1表示資料,3自動計算-1 = 5
array([[0, 2, 3],
       [7, 1, 2],
       [1, 9, 3],
       [0, 3, 3],
       [8, 7, 1]])

6.2 陣列轉置

# 轉置,行變列,列變行
a.T # 矩陣 shape = (5,3)
array([[0, 2, 3],
       [2, 1, 3],
       [3, 9, 8],
       [7, 3, 7],
       [1, 0, 1]])
np.transpose(a,(1,0)) # 行0,列1,默認情況下(0,1)----->調整(1,0)
array([[0, 2, 3],
       [2, 1, 3],
       [3, 9, 8],
       [7, 3, 7],
       [1, 0, 1]])
b = np.random.randint(0,10,size = (3,5,7)) # shape = (0,1,2)
b
array([[[3, 0, 4, 0, 4, 8, 0],
        [6, 2, 2, 1, 6, 0, 4],
        [9, 5, 2, 8, 8, 6, 2],
        [0, 6, 2, 8, 0, 0, 5],
        [4, 3, 2, 3, 4, 0, 0]],

       [[6, 7, 8, 5, 5, 4, 9],
        [3, 0, 5, 6, 8, 6, 4],
        [9, 3, 5, 5, 6, 4, 6],
        [3, 0, 5, 9, 2, 7, 4],
        [5, 5, 4, 7, 8, 2, 9]],

       [[6, 8, 6, 8, 3, 1, 7],
        [7, 9, 1, 3, 9, 3, 2],
        [1, 9, 7, 7, 4, 2, 8],
        [9, 6, 7, 3, 6, 0, 9],
        [3, 3, 6, 2, 5, 2, 5]]])
c = np.transpose(b,(2,1,0)) # 就是調整維度結構2和0維度資料對調
c.shape
(7, 5, 3)

6.3 資料堆疊合并

nd1 = np.random.randint(0,10,size = (3,5))
nd2 = np.random.randint(0,10,size = (3,5))
display(nd1,nd2)
array([[5, 1, 3, 3, 4],
       [3, 0, 9, 3, 7],
       [2, 9, 3, 8, 4]])



array([[1, 9, 9, 0, 7],
       [7, 8, 8, 0, 8],
       [6, 0, 9, 3, 3]])
np.concatenate([nd1,nd2]) # 默認合并行增加
array([[5, 1, 3, 3, 4],
       [3, 0, 9, 3, 7],
       [2, 9, 3, 8, 4],
       [1, 9, 9, 0, 7],
       [7, 8, 8, 0, 8],
       [6, 0, 9, 3, 3]])
# 修改axis引數調整資料合并方向
np.concatenate([nd1,nd2],axis = 1) # axis 軸,方向 0 = 行,1 = 列
array([[5, 1, 3, 3, 4, 1, 9, 9, 0, 7],
       [3, 0, 9, 3, 7, 7, 8, 8, 0, 8],
       [2, 9, 3, 8, 4, 6, 0, 9, 3, 3]])
np.hstack((nd1,nd2)) # 堆疊,摞起來,增多,合并 h表示水平,列增多
array([[5, 1, 3, 3, 4, 1, 9, 9, 0, 7],
       [3, 0, 9, 3, 7, 7, 8, 8, 0, 8],
       [2, 9, 3, 8, 4, 6, 0, 9, 3, 3]])
np.vstack((nd1,nd2,nd2,nd2,nd1)) # v 豎直,行增加
array([[5, 1, 3, 3, 4],
       [3, 0, 9, 3, 7],
       [2, 9, 3, 8, 4],
       [1, 9, 9, 0, 7],
       [7, 8, 8, 0, 8],
       [6, 0, 9, 3, 3],
       [1, 9, 9, 0, 7],
       [7, 8, 8, 0, 8],
       [6, 0, 9, 3, 3],
       [1, 9, 9, 0, 7],
       [7, 8, 8, 0, 8],
       [6, 0, 9, 3, 3],
       [5, 1, 3, 3, 4],
       [3, 0, 9, 3, 7],
       [2, 9, 3, 8, 4]])
a = np.random.randint(0,10,size = (3,5))
b = np.random.randint(0,10,size = (3,6))
display(a,b)
np.concatenate([a,b]) # 報錯
array([[2, 5, 3, 6, 8],
       [0, 8, 1, 2, 3],
       [6, 0, 7, 1, 2]])



array([[0, 9, 6, 2, 4, 8],
       [3, 0, 0, 0, 8, 3],
       [7, 3, 1, 3, 7, 0]])



---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-205-16b2fe89e6c7> in <module>
      2 b = np.random.randint(0,10,size = (3,6))
      3 display(a,b)
----> 4 np.concatenate([a,b]) # 報錯


<__array_function__ internals> in concatenate(*args, **kwargs)


ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 5 and the array at index 1 has size 6
np.concatenate([a,b],axis =1)   # 報錯
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-242-9acf5d5d319b> in <module>
----> 1 np.concatenate([a,b],axis =1)


<__array_function__ internals> in concatenate(*args, **kwargs)


ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)

6.4 陣列拆分

a = np.random.randint(0,100,size = (15,10))
a
array([[73, 62, 19,  9, 90, 98, 38, 91, 14, 72],
       [64, 34, 80, 81, 77, 83, 69, 84,  5, 42],
       [29, 79, 49, 87, 15,  9, 98, 68, 33, 72],
       [ 0, 89, 36, 54, 11, 12, 27, 39, 14, 11],
       [26, 84, 21, 94, 18, 32, 64, 31, 64, 39],
       [45,  0, 61, 18, 16, 29, 77, 34, 18, 86],
       [10, 63, 81, 38, 44, 47, 28, 96, 54, 53],
       [67, 50, 24, 15, 42, 10, 18, 92, 41, 42],
       [61,  0, 67, 41, 13, 87, 82, 57, 54, 50],
       [32, 69, 72, 33, 56, 12, 12, 66, 55, 94],
       [49, 45, 68, 15, 24, 51, 18, 18, 59, 47],
       [77, 58, 93, 79, 89, 63, 41, 82,  8, 20],
       [70, 84, 75, 67, 39, 53, 32, 31, 20, 37],
       [20, 51, 54, 30,  5, 71, 59, 51, 96, 68],
       [52, 31, 73, 56, 60,  3, 81,  2,  7, 69]])
np.split(a,indices_or_sections=5) # 給數字,表示平均分成多少分
[array([[73, 62, 19,  9, 90, 98, 38, 91, 14, 72],
        [64, 34, 80, 81, 77, 83, 69, 84,  5, 42],
        [29, 79, 49, 87, 15,  9, 98, 68, 33, 72]]),
 array([[ 0, 89, 36, 54, 11, 12, 27, 39, 14, 11],
        [26, 84, 21, 94, 18, 32, 64, 31, 64, 39],
        [45,  0, 61, 18, 16, 29, 77, 34, 18, 86]]),
 array([[10, 63, 81, 38, 44, 47, 28, 96, 54, 53],
        [67, 50, 24, 15, 42, 10, 18, 92, 41, 42],
        [61,  0, 67, 41, 13, 87, 82, 57, 54, 50]]),
 array([[32, 69, 72, 33, 56, 12, 12, 66, 55, 94],
        [49, 45, 68, 15, 24, 51, 18, 18, 59, 47],
        [77, 58, 93, 79, 89, 63, 41, 82,  8, 20]]),
 array([[70, 84, 75, 67, 39, 53, 32, 31, 20, 37],
        [20, 51, 54, 30,  5, 71, 59, 51, 96, 68],
        [52, 31, 73, 56, 60,  3, 81,  2,  7, 69]])]
np.split(a,indices_or_sections=2,axis =1) # axis = 1 表示列,平均分成兩份
[array([[73, 62, 19,  9, 90],
        [64, 34, 80, 81, 77],
        [29, 79, 49, 87, 15],
        [ 0, 89, 36, 54, 11],
        [26, 84, 21, 94, 18],
        [45,  0, 61, 18, 16],
        [10, 63, 81, 38, 44],
        [67, 50, 24, 15, 42],
        [61,  0, 67, 41, 13],
        [32, 69, 72, 33, 56],
        [49, 45, 68, 15, 24],
        [77, 58, 93, 79, 89],
        [70, 84, 75, 67, 39],
        [20, 51, 54, 30,  5],
        [52, 31, 73, 56, 60]]),
 array([[98, 38, 91, 14, 72],
        [83, 69, 84,  5, 42],
        [ 9, 98, 68, 33, 72],
        [12, 27, 39, 14, 11],
        [32, 64, 31, 64, 39],
        [29, 77, 34, 18, 86],
        [47, 28, 96, 54, 53],
        [10, 18, 92, 41, 42],
        [87, 82, 57, 54, 50],
        [12, 12, 66, 55, 94],
        [51, 18, 18, 59, 47],
        [63, 41, 82,  8, 20],
        [53, 32, 31, 20, 37],
        [71, 59, 51, 96, 68],
        [ 3, 81,  2,  7, 69]])]
# 引數給串列,根據串列中的索引,進行切片
np.split(a,indices_or_sections=[1,5,9]) # 0~1,1~5,5~9,9~
[array([[73, 62, 19,  9, 90, 98, 38, 91, 14, 72]]),
 array([[64, 34, 80, 81, 77, 83, 69, 84,  5, 42],
        [29, 79, 49, 87, 15,  9, 98, 68, 33, 72],
        [ 0, 89, 36, 54, 11, 12, 27, 39, 14, 11],
        [26, 84, 21, 94, 18, 32, 64, 31, 64, 39]]),
 array([[45,  0, 61, 18, 16, 29, 77, 34, 18, 86],
        [10, 63, 81, 38, 44, 47, 28, 96, 54, 53],
        [67, 50, 24, 15, 42, 10, 18, 92, 41, 42],
        [61,  0, 67, 41, 13, 87, 82, 57, 54, 50]]),
 array([[32, 69, 72, 33, 56, 12, 12, 66, 55, 94],
        [49, 45, 68, 15, 24, 51, 18, 18, 59, 47],
        [77, 58, 93, 79, 89, 63, 41, 82,  8, 20],
        [70, 84, 75, 67, 39, 53, 32, 31, 20, 37],
        [20, 51, 54, 30,  5, 71, 59, 51, 96, 68],
        [52, 31, 73, 56, 60,  3, 81,  2,  7, 69]])]
np.hsplit(a,indices_or_sections=2) # h水平,列方向上分割成了兩份
[array([[73, 62, 19,  9, 90],
        [64, 34, 80, 81, 77],
        [29, 79, 49, 87, 15],
        [ 0, 89, 36, 54, 11],
        [26, 84, 21, 94, 18],
        [45,  0, 61, 18, 16],
        [10, 63, 81, 38, 44],
        [67, 50, 24, 15, 42],
        [61,  0, 67, 41, 13],
        [32, 69, 72, 33, 56],
        [49, 45, 68, 15, 24],
        [77, 58, 93, 79, 89],
        [70, 84, 75, 67, 39],
        [20, 51, 54, 30,  5],
        [52, 31, 73, 56, 60]]),
 array([[98, 38, 91, 14, 72],
        [83, 69, 84,  5, 42],
        [ 9, 98, 68, 33, 72],
        [12, 27, 39, 14, 11],
        [32, 64, 31, 64, 39],
        [29, 77, 34, 18, 86],
        [47, 28, 96, 54, 53],
        [10, 18, 92, 41, 42],
        [87, 82, 57, 54, 50],
        [12, 12, 66, 55, 94],
        [51, 18, 18, 59, 47],
        [63, 41, 82,  8, 20],
        [53, 32, 31, 20, 37],
        [71, 59, 51, 96, 68],
        [ 3, 81,  2,  7, 69]])]
np.vsplit(a,indices_or_sections=[3,7,11]) # v表示豎直,行切片,行分割
[array([[73, 62, 19,  9, 90, 98, 38, 91, 14, 72],
        [64, 34, 80, 81, 77, 83, 69, 84,  5, 42],
        [29, 79, 49, 87, 15,  9, 98, 68, 33, 72]]),
 array([[ 0, 89, 36, 54, 11, 12, 27, 39, 14, 11],
        [26, 84, 21, 94, 18, 32, 64, 31, 64, 39],
        [45,  0, 61, 18, 16, 29, 77, 34, 18, 86],
        [10, 63, 81, 38, 44, 47, 28, 96, 54, 53]]),
 array([[67, 50, 24, 15, 42, 10, 18, 92, 41, 42],
        [61,  0, 67, 41, 13, 87, 82, 57, 54, 50],
        [32, 69, 72, 33, 56, 12, 12, 66, 55, 94],
        [49, 45, 68, 15, 24, 51, 18, 18, 59, 47]]),
 array([[77, 58, 93, 79, 89, 63, 41, 82,  8, 20],
        [70, 84, 75, 67, 39, 53, 32, 31, 20, 37],
        [20, 51, 54, 30,  5, 71, 59, 51, 96, 68],
        [52, 31, 73, 56, 60,  3, 81,  2,  7, 69]])]

七、廣播機制

arr1 = np.array([0,1,2,3]*3)
arr1.sort() # 排序,從小到大
arr1 = arr1.reshape(4,3)
arr1
array([[0, 0, 0],
       [1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])
arr2 = np.array([1,2,3])
display(arr1,arr2) # 形狀不對應,依然可以進行運算:NumPy底層,為我們進行了廣播
array([[0, 0, 0],
       [1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])



array([1, 2, 3])
# 行不夠,廣播行
arr1 + arr2 # arr2 和arr1 中每一行,進行相加:廣播機制 
array([[1, 2, 3],
       [2, 3, 4],
       [3, 4, 5],
       [4, 5, 6]])
arr3 = np.array([[1],[2],[3],[4]])
display(arr1,arr3)
array([[0, 0, 0],
       [1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])



array([[1],
       [2],
       [3],
       [4]])
# 列不夠,廣播列
arr1 + arr3 # 廣播,arr2和arr1中每一列,進行相加:廣播
array([[1, 1, 1],
       [3, 3, 3],
       [5, 5, 5],
       [7, 7, 7]])
# 廣播,和復制,意思有點近似
a = np.array([0,1,2,3,4,5,6,7]*3).reshape(3,4,2)
a
array([[[0, 1],
        [2, 3],
        [4, 5],
        [6, 7]],

       [[0, 1],
        [2, 3],
        [4, 5],
        [6, 7]],

       [[0, 1],
        [2, 3],
        [4, 5],
        [6, 7]]])
b = np.array([0,1,2,3,4,5,6,7]).reshape(4,2)
b
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7]])
display(a.shape,b.shape)
(3, 4, 2)



(4, 2)
a * b # b形狀(4,2),b 廣播了三份
array([[[ 0,  1],
        [ 4,  9],
        [16, 25],
        [36, 49]],

       [[ 0,  1],
        [ 4,  9],
        [16, 25],
        [36, 49]],

       [[ 0,  1],
        [ 4,  9],
        [16, 25],
        [36, 49]]])

八、通用函式

8.1 元素級數字級別的方法

# abs、sqrt、square、exp、log、sin、cos、tan,maxinmum、minimum、
# all、any、inner、clip、round、trace、ceil、floor
a = np.array([-1,-3,-5,1,5,8,9])
c = np.random.randint(-5,10,size = 7)
display(a,c)
array([-1, -3, -5,  1,  5,  8,  9])



array([ 2, -3, -4,  7,  7,  7, -2])
np.abs(a) # 求絕對值
array([1, 3, 5, 1, 5, 8, 9])
b = np.array([1,4,9,16,36,49])
b
array([ 1,  4,  9, 16, 36, 49])
np.sqrt(b) # 開平發
array([1., 2., 3., 4., 6., 7.])
np.square(b) # 平方
np.exp(3) # 自然底數e的多少次冪
np.log(20.085536) # 自然底數e對數求解
np.sin(np.pi/2) # 90度sin正弦值
np.cos(0) # 余弦值
np.tan(np.pi/6) # 正切,30度正切值
# 給兩個陣列,從中選取大的,或者選取小的
np.maximum(a,c) # 從a和c中選取最大的值
np.minimum(a,c) # 選取最小的值
array([-1, -3, -5,  1,  5,  7, -2])
nd1 = np.array([1,3,0]) # 出現0那么對應False,非零True
nd2 = np.array([-1,-3,4,8])
display(nd1,nd2)
array([1, 3, 0])



array([-1, -3,  4,  8])
nd1.any() # 只要有一個True,回傳True
True
nd1.all() # 所有True,回傳True
False
nd2.all() # 所有的都是True,回傳True
True
a = np.array([1,2,3,4,5])
b = np.array([1,2,3,4,6])
np.inner(a,b) # 1*1 + 2*2 + 3*3 + 4*4 + 5*6 = 60
# 回傳的是兩個陣列的內積,對應位置相乘加和
60
nd1 = np.random.randint(0,100,size = 30)
nd1
array([61, 15, 31, 92, 91, 24, 20, 59,  6, 41, 46,  8, 30, 37, 53, 70, 59,
       24, 66, 43, 36, 95, 14,  7, 67, 86, 53, 26, 70, 62])
np.clip(nd1,10,80) # 資料裁剪,將小于10變成10,將大于80的變成80
array([61, 15, 31, 80, 80, 24, 20, 59, 10, 41, 46, 10, 30, 37, 53, 70, 59,
       24, 66, 43, 36, 80, 14, 10, 67, 80, 53, 26, 70, 62])
nd2  = np.random.randn(20)
nd2
array([ 0.5020347 , -0.60462332, -1.17663827, -0.37269518, -1.42816971,
        0.023136  ,  0.782975  ,  0.30537136, -0.43498012, -1.08404953,
        0.85617269,  1.16387006, -0.01622137,  1.21683923, -0.29338921,
       -2.78006002,  0.07321195,  1.11264868, -0.70013613, -1.2466278 ])
nd2.round(2)
array([ 0.5 , -0.6 , -1.18, -0.37, -1.43,  0.02,  0.78,  0.31, -0.43,
       -1.08,  0.86,  1.16, -0.02,  1.22, -0.29, -2.78,  0.07,  1.11,
       -0.7 , -1.25])
np.ceil(np.array([2.7,2.1,2.05])) # 天花板,向上取整
array([3., 3., 3.])
np.floor(np.array([2.99,2.9999,2.1])) # 向下取整
array([2., 2., 2.])
a = np.random.randint(0,10,size = (3,3))
a
array([[6, 5, 1],
       [7, 3, 6],
       [9, 1, 3]])
np.trace(a) # 就算對角線上的和
12

8.2 where函式

import numpy as np
nd1 = np.array([1,3,5,7,9])
nd2 = np.array([2,4,6,8,10])
cond = np.array([True,False,False,True,True])
np.where(cond,nd1,nd2) # 條件如果是True,那么回傳nd1中資料,如果Flase回傳nd2中資料
array([1, 4, 6, 7, 9])
a = np.random.randint(0,100,size = 50)
display(a) # 資料展示
np.where(a > 50,a,a + 20) # 大于50,回傳多少;不然回傳-100
array([86, 27, 93, 30, 55, 13, 37, 60,  1,  6, 44, 77, 74, 11, 71, 95, 45,
       32,  0, 40, 13, 23, 38,  4, 36, 96, 81, 10, 79, 90, 13, 19, 15, 50,
       90, 20, 51, 56, 56, 42, 86, 41, 35, 33, 33, 46, 69, 35, 50, 15])





array([86, 47, 93, 50, 55, 33, 57, 60, 21, 26, 64, 77, 74, 31, 71, 95, 65,
       52, 20, 60, 33, 43, 58, 24, 56, 96, 81, 30, 79, 90, 33, 39, 35, 70,
       90, 40, 51, 56, 56, 62, 86, 61, 55, 53, 53, 66, 69, 55, 70, 35])
# 如果分數50~59分之間,自動加10分
a = np.random.randint(0,100,size = 50)
a
array([39, 55, 20, 11, 12,  5, 46, 55, 37, 90, 93, 33, 24, 53, 91, 82, 82,
       64, 25, 12, 74, 64, 73, 10, 50, 35, 87, 81, 59, 62, 85,  0, 53,  0,
       49, 99, 54, 82, 26, 52, 28, 66, 63, 79, 57, 70, 82, 38, 95, 58])
cond = (a >=50) & (a < 60) # 與運算
np.where(cond,a + 10,a)
array([39, 65, 20, 11, 12,  5, 46, 65, 37, 90, 93, 33, 24, 63, 91, 82, 82,
       64, 25, 12, 74, 64, 73, 10, 60, 35, 87, 81, 69, 62, 85,  0, 63,  0,
       49, 99, 64, 82, 26, 62, 28, 66, 63, 79, 67, 70, 82, 38, 95, 68])

8.3 排序

a = np.random.randint(0,100,size = 20)
a
array([45, 66, 26, 25, 69, 35, 31, 24, 73,  3, 14, 82, 21, 86, 56,  7, 36,
       39,  9, 28])
b = np.sort(a) # 列印輸出,那么,原陣列,沒有改變
b
array([ 3,  7,  9, 14, 21, 24, 25, 26, 28, 31, 35, 36, 39, 45, 56, 66, 69,
       73, 82, 86])
a.sort() # 沒有輸出,說明,原陣列上進行了排序
a
array([ 3,  7,  9, 14, 21, 24, 25, 26, 28, 31, 35, 36, 39, 45, 56, 66, 69,
       73, 82, 86])
index = a.argsort() # 回傳排序的索引
display(index)
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19], dtype=int64)
# 根據索引,花式索引
a[index][::-1]
array([86, 82, 73, 69, 66, 56, 45, 39, 36, 35, 31, 28, 26, 25, 24, 21, 14,
        9,  7,  3])

8.4 集合操作

a = np.random.randint(0,30,size = 15)
b = np.random.randint(0,30,size = 15)
display(a,b)
array([28,  9, 20, 24, 10,  7, 18, 23,  6, 28,  4, 13, 14,  6,  6])



array([16, 25,  4, 23, 23,  4, 24, 26,  0,  8, 15,  6,  5, 23, 11])
np.intersect1d(a,b) # 交集:a和b中都有
array([ 4,  6, 23, 24])
np.union1d(a,b) # 并集:a和b中的所有,合并
array([ 0,  4,  5,  6,  7,  8,  9, 10, 11, 13, 14, 15, 16, 18, 20, 23, 24,
       25, 26, 28])
np.setdiff1d(a,b) # 差集,a中有,b中沒有
array([ 7,  9, 10, 13, 14, 18, 20, 28])

8.5 數學和統計函式

min、max、mean、median、sum、std、var、cumsum、cumprod、argmin、argmax、argwhere、cov、corrcoef

a = np.random.randint(0,100,size = (3,5))
a
array([[30, 38, 14, 95, 19],
       [11, 32, 55, 94, 33],
       [59, 64, 41, 12,  1]])
a.min()
1
a.max(axis = 0) # axis 軸,方向,axis = 0 行,axis = 1列
array([59, 64, 55, 95, 33])
a.max(axis = 1)
array([95, 94, 64])
a.mean() # 平均值
39.86666666666667
np.median(a) # 中位數
33.0
a.sum() # 求和
598
a.std() # 標準差
27.789366471528076
a.var() # 方差,資料內部波動
772.2488888888888
a.cumsum() # 累計和
array([ 30,  68,  82, 177, 196, 207, 239, 294, 388, 421, 480, 544, 585,
       597, 598], dtype=int32)
b = np.array([1,2,3,4,5,6,7])
b.cumprod() # 累乘和
array([   1,    2,    6,   24,  120,  720, 5040], dtype=int32)
a.argmin() # 回傳最小值的索引
14
a.argmax() # 回傳最大值的索引
3
a
array([[30, 38, 14, 95, 19],
       [11, 32, 55, 94, 33],
       [59, 64, 41, 12,  1]])
index = np.argwhere((a > 50) | (a < 20)) # 回傳就是符合條件的索引
index
array([[0, 2],
       [0, 3],
       [0, 4],
       [1, 0],
       [1, 2],
       [1, 3],
       [2, 0],
       [2, 1],
       [2, 3],
       [2, 4]], dtype=int64)
for i,j in index:
    print(a[i,j])
14
95
19
11
55
94
59
64
12
1
# cov 協方差(屬性之間進行計算),方差概念類似(資料內部,屬性內部計算)
# 舉例子:一個男生受女生歡迎程度,和這名男生萎縮程度,是否成正比,什么關系
np.cov(a)
array([[1060.7 ,  763.25, -250.85],
       [ 763.25,  992.5 , -463.  ],
       [-250.85, -463.  ,  784.3 ]])
np.corrcoef(a) # 相關性系數,1(正相關) ~ -1(負相關)
# 0 表示,沒有關系
array([[ 1.        ,  0.74388409, -0.27502788],
       [ 0.74388409,  1.        , -0.5247768 ],
       [-0.27502788, -0.5247768 ,  1.        ]])

九、線性代數

A = np.random.randint(0,10,size = (3,3))

B = np.random.randint(0,10,size = (3,4))
display(A,B) # A矩陣行長度必須和B列長度一致,不然報錯
array([[3, 1, 2],
       [5, 4, 8],
       [8, 6, 5]])



array([[3, 6, 2, 0],
       [6, 2, 8, 2],
       [0, 1, 4, 5]])
A.dot(B) # dot矩陣乘法 ,點乘
array([[15, 22, 22, 12],
       [39, 46, 74, 48],
       [60, 65, 84, 37]])
np.dot(A,B) # 模塊提供的方法
array([[15, 22, 22, 12],
       [39, 46, 74, 48],
       [60, 65, 84, 37]])
A @ B # 郵件中@符號,表示矩陣運算
array([[15, 22, 22, 12],
       [39, 46, 74, 48],
       [60, 65, 84, 37]])
C = np.random.randint(0,10,size = (4,5))
C
array([[1, 3, 1, 5, 7],
       [0, 0, 1, 1, 3],
       [9, 2, 3, 4, 5],
       [2, 7, 3, 6, 2]])
A.dot(C) # 形狀不對應,無法進行矩陣乘法
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-384-f96e5078725a> in <module>
----> 1 A.dot(C) # 形狀不對應,無法進行矩陣乘法


ValueError: shapes (3,3) and (4,5) not aligned: 3 (dim 1) != 4 (dim 0)
# B.shape = (3,4);C.shape = (4,5)
B.dot(C)
array([[21, 13, 15, 29, 49],
       [82, 48, 38, 76, 92],
       [46, 43, 28, 47, 33]])
# C.shape = (4,5);B.shape = (3,4)
C.dot(B) # 矩陣乘法不滿足交換律!!!
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-386-0ff241fbe642> in <module>
      1 # C.shape = (4,5);B.shape = (3,4)
----> 2 C.dot(B) # 矩陣乘法不滿足交換律!!!


ValueError: shapes (4,5) and (3,4) not aligned: 5 (dim 1) != 3 (dim 0)

結束語

本篇博文的代碼是在jupyter上運行的,不過具體在哪運行都沒什么大的區別,

感謝收看,祝學業和作業進步! 需要本文資料的話,歡迎關注評論留下你的郵箱,


推薦關注的專欄

👨?👩?👦?👦 機器學習:分享機器學習實戰專案和常用模型講解
👨?👩?👦?👦 資料分析:分享資料分析實戰專案和常用技能整理

往期內容回顧

💚 學習Python全套代碼【超詳細】Python入門、核心語法、資料結構、Python進階【致那個想學好Python的你】
?? 學習pandas全套代碼【超詳細】資料查看、輸入輸出、選取、集成、清洗、轉換、重塑、數學和統計方法、排序
💙 學習pandas全套代碼【超詳細】分箱操作、分組聚合、時間序列、資料可視化


關注我,了解更多相關知識!

CSDN@報告,今天也有好好學習

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/352231.html

標籤:python

上一篇:在國內吹上天的Python真的簡單嗎?易學難精啊

下一篇:用python處理28萬條人人貸資料,告訴你最詳細的借款人結構分布情況

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more