天天看點

python3 ---numpy 練習題 (附詳細答案,做題心得)

1.

Q:将 numpy 導入為 np 并檢視版本号。

參考答案:

import numpy as np
print(np.__version__)

輸出:1.20.3      

2.

Q:建立一個從0到9的一維數組。

三種方法都可以。arange用法和range用法相同。

參考答案:

res = np.array([0,1,2,3,4,5,6,7,8,9])
res = np.array(range(10))
res = np.arange(10)

輸出都是:[0 1 2 3 4 5 6 7 8 9]      

3.

Q:建立一個3×3的所有真值的數組。

參考答案:

res = np.full((3,3),True,dtype=bool)

輸出:
[[ True  True  True]
 [ True  True  True]
 [ True  True  True]]      

解釋一下 full函數.

full(形狀,填充數值,數值類型)

​​

​numpy.full(shape, fill_value, dtype=None, order='C')​

​​ order: : {‘C’, ‘F’}, 可選參數

是否以C或Fortran-contiguous(行或列)順序存儲多元資料。

4.

Q:從 arr 中提取所有奇數.

參考答案:

arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
res = arr[arr%2==1]
輸出:[1 3 5 7 9]      

5.

Q:用-1替換 arr 中的所有奇數

參考答案:

arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
arr[arr%2==1] = -1
輸出:[ 0 -1  2 -1  4 -1  6 -1  8 -1]      

6.

Q:在不改變 arr 的情況下,用1代替 arr 中的所有奇數.

參考答案:

arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
res = np.where(arr % 2 == 1,-1,arr)
輸出res:[ 0 -1  2 -1  4 -1  6 -1  8 -1]
輸出arr:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      

where函數的兩種用法:

1.np.where(condition, x, y)

滿足條件(condition),輸出x,不滿足輸出y。

2.np.where(condition)

隻有條件 (condition),沒有x和y,則輸出滿足條件 (即非0) 元素的坐标。

7.

Q:将一維數組轉換成2行的2D數組.

參考答案:

arr = np.arange(10)
res = np.reshape(arr,(2,5))
輸出:
arr:[0 1 2 3 4 5 6 7 8 9]
res:[[0 1 2 3 4]
 [5 6 7 8 9]]      

8.

Q:垂直排列數組A和B.

參考答案:

a = np.arange(10).reshape(2,-1)
b = np.repeat(1, 10).reshape(2,-1)

res = np.vstack([a,b])
輸出:

a:[[0 1 2 3 4]
 [5 6 7 8 9]]
 
b:[[1 1 1 1 1]
 [1 1 1 1 1]]
 
res:
[[0 1 2 3 4]
 [5 6 7 8 9]
 [1 1 1 1 1]
 [1 1 1 1 1]]      

9.

Q:水準排列兩數組A和B.

參考答案:

a = np.arange(10).reshape(2,-1)
b = np.repeat(1, 10).reshape(2,-1)
res = np.hstack([a,b])
輸出:
[[0 1 2 3 4 1 1 1 1 1]
 [5 6 7 8 9 1 1 1 1 1]]      

10.

Q:擷取A和B之間的公共項

參考答案:

a = np.array([1,2,3,2,3,4,3,4,5,6])
b = np.array([7,2,10,2,7,4,9,4,9,8])
res = np.intersect1d(a,b)
print(res)
輸出:
[2 4]      

11.

Q:在沒有寫死的情況下建立下面的數組。​

​array([1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3])​

​ 隻使用numpy函數和下面的輸入數組a。

a = np.array([1,2,3])
np.r_[np.repeat(a, 3), np.tile(a, 3)]
輸出:
array([1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3])      

r_ : 按行拼接

12.

Q:從數組A移除數組B中存在的所有項.

參考答案:

a = np.array([1,2,3,4,5])
b = np.array([5,6,7,8,9])
res = np.setdiff1d(a,b)
print(res)
輸出:
[1 2 3 4]      

13.

Q:擷取A和B元素比對的位置

a = np.array([1,2,3,2,3,4,3,4,5,6])
b = np.array([7,2,10,2,7,4,9,4,9,8])
res = np.where(a == b)
print(res)
輸出:
(array([1, 3, 5, 7]),)      

14.

Q:從A中擷取5到10之間的所有項。

= np.array([2, 6, 1, 9, 10, 3, 27])

法一:
res = np.where((a >=5) & (a <= 10))
print(res)
輸出:(array([1, 3, 4]),)

法二:

res = a[(a >=5) & (a <= 10)]
print(res)
輸出:[ 6  9 10]      

這裡要注意,where傳回的是符合條件的值的索引

而直接使用 arr[條件],傳回符合條件的值。

15.

Q:轉換适用于兩個标量的函數maxx,以處理兩個數組。

待解決。。。。。

16.

Q:在數組arr中交換列1和2。

參考答案:

= np.arange(9).reshape(3,3)
res = arr[:,[1,0,2]]
print(res)      

切片和python的切片文法大緻一樣。​

​arr[:,[1,0,2]]​

​ 逗号前面的分号前後都沒有值,表示取所有行。逗号後面為[1,0,2] 表示取第1,0,2行(書寫與傳回順序一緻)

17.

Q:在數組arr中交換兩行1和2

參考答案:

arr = np.arange(9).reshape(3,3)
res = arr[[1,0,2],:]
print(res)      

18.

Q:反轉二維數組arr的行

參考答案:

arr = np.arange(9).reshape(3,3)
res = arr[::-1,:]
print(res)      

看到網上很多答案是 ​

​res = arr[::-1]​

​​ 這樣不夠精确也不便于了解。

​​

​arr[::-1,:]​

​ 顯然逗号前面是操作行,後面操作列。表示取全部行,-1就是步長,與python裡的切片一樣表示翻轉。

19.

Q:反轉二維數組 arr 的列

參考答案:

arr = np.arange(9).reshape(3,3)
res = arr[:,::-1]
print(res)      

20.

Q:建立一個形狀為5x3的二維數組,包含5到10之間的随機十進制浮點數。

參考答案:

arr = np.random.uniform(5,10,(5,3))      

21,

Q:隻列印或顯示numpy數組rand_arr的小數點後三位。

參考答案:

np.set_printoptions(precision=3) # 沒有任何接收值什麼的。直接在需要控制的語句上面寫就行了
rand_arr = np.random.random([5,3])      

22.

Q:通過e式科學記數法來列印rand_arr(如1e10)

參考答案:

np.set_printoptions(suppress=False)
rand_arr = np.random.random([3,3])/1e3
print(rand_arr)
np.set_printoptions(suppress=True)
print(rand_arr)

前後輸出對比:
[[8.86114528e-04 2.35134440e-04 8.55421233e-04]
 [5.52686672e-04 3.89532450e-04 4.37608757e-04]
 [1.91159998e-05 6.21107903e-04 8.97569376e-04]]
[[0.00088611 0.00023513 0.00085542]
 [0.00055269 0.00038953 0.00043761]
 [0.00001912 0.00062111 0.00089757]]      

np.set_printoptions(precision=None, threshold=None, suppress=None)

  • precision:控制輸出的小數點個數,預設是8
  • threshold:控制輸出的值的個數,其餘以…代替;

    當設定列印顯示方式threshold=np.nan,意思是輸出數組的時候完全輸出,不需要省略号将中間資料省略

  • suppress: 當suppress=True,表示小數不需要以科學計數法的形式輸出

23.

Q:将numpy數組a中列印的項數限制為最多6個元素。

參考答案:

np.set_printoptions(threshold=6)
a = np.arange(15)
print(a)
輸出[ 0  1  2 ... 12 13 14]      

24.

Q:列印完整的numpy數組a而不截斷。

上一題中 使用了函數将中間一寫值用省略号來表示了。

如果想再次全部顯示,隻需要設定 ​​

​threshold = np.nan​

25.

Q:從數組a中,将大于30的替換為30,小于10的替換為10

參考答案:

np.random.seed(100)
a = np.random.uniform(1,50, 20)
res = np.clip(a,10,30)
print(res)      

clip(數組,小于N的變成N,大于X的變成X)

26.

Q:擷取給定數組a中前5個最大值的位置。

參考答案:

np.random.seed(100)
a = np.random.uniform(1,50, 20)
print(a)
res = np.max(a[0:6],axis=0)
res = np.where(res)
print(res)

輸出:
[27.62684215 14.64009987 21.80136195 42.39403048  1.23122395  6.95688692
 33.86670515 41.466785    7.69862289 29.17957314 44.67477576 11.25090398
 10.08108276  6.31046763 11.76517714 48.95256545 40.77247431  9.42510962
 40.99501269 14.42961361]
(array([0]),)      

27.

Q:将res_9轉換為扁平線性1d數組。

參考答案:

res_9 = np.arange(24).reshape((4,6))
res_10 = res_9.flatten()


res_9:
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]]
res_10:
 [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]      

27.

Q:按行計算唯一值的計數。

參考答案:

.random.seed(100)
arr = np.random.randint(1,11,size=(6, 10))
res = []

for i in arr:
    temp = []
    for j in range(1,11):
        i = str(i)
        temp.append(i.count(str(j)))
    # print(temp)
    res.append(temp)
print(res)      

28,

Q:計算給定數組中每行的最大值。

參考答案:

np.random.seed(100)
a = np.random.randint(1,10, [5,3])
print(a)


res = np.max(a,axis = 1)
print(res)

輸出:
[[9 9 4]
 [8 8 1]
 [5 3 6]
 [3 3 3]
 [2 1 9]]
[9 8 6 3 9]      

29.

Q:在給定的numpy數組中找到重複的條目(第二次出現以後),并将它們标記為True。第一次出現應該是False的。

參考答案:

a = np.arange(10)
res = np.full(a.shape, True)

Array=[0,0,3 ,0, 2, 4, 2, 2, 2, 2]
b = np.unique(Array,return_index=True)[1]
res[b] = False
print(res)      

full函數就是填充數組内的值,使用後面的那個參數。

unique函數 去重的作用,return_index=True,傳回去重之後的元素下标。

30.

Q:從一維numpy數組中删除所有NaN值

參考答案:

a = np.array([1,2,3,np.nan,5,6,7,np.nan])
res = np.isnan(a)
print(res)
res = np.delete(a,res)
print(res)

輸出:
[False False False  True False False False  True]
[1. 2. 3. 5. 6. 7.]      

isnan()将為nan的位置設定為True其他為False

delete() 删除

31.

Q:從2d數組a_2d中減去一維數組b_1D.

參考答案:

a_2d = np.array([[3,3,3],[4,4,4],[5,5,5]])
b_1d = np.array([1,1,1])
res = a_2d - b_1d
print(res)

輸出:
[[2 2 2]
 [3 3 3]
 [4 4 4]]      

32.

Q:找出x中數字1的第5次重複的索引。

參考答案:

x = np.array([1, 2, 1, 1, 3, 4, 3, 1, 1, 2, 1, 1, 2])

temp = 0
for index,val in enumerate(x):
    if val == 1:
        temp +=1
    if temp == 6:
        print(index)
        break
輸出:10      

這道題要找到數字1的第五次重複位置的下标,

網上的答案給的5顯然是不對的。

注意這裡是第五次重複。也就是第六次1出現的位置。

33.

Q:将numpy的datetime64對象轉換為datetime的datetime對象

參考答案:

import numpy as np

from  datetime import datetime
dt64 = np.datetime64('2018-02-25 22:10:10')

print(dt64)
res = dt64.astype(datetime)
print(res)      

34.

Q:建立長度為10的numpy數組,從5開始,在連續的數字之間的步長為3。

length = 10
start = 5
step = 3

leng = 5 + 3*10

res = np.arange(5,leng,3)
print(res)      

35.