NumPy測試題


122

     NumPy 是 Python 科學計算的基礎軟件包

        提供多維數組對象,多種派生對象(掩碼數組、矩陣等)以及用於快速操作數組的函數及 API,它包括數學、邏輯、數組形狀變換、排序、選擇、I/O 、離散傅立葉變換、基本線性代數、基本統計運算、隨機模擬等等。

70道NumPy測試題~

1. 將 NumPy 導入為 np,並查看版本

問題:將 NumPy 導入為 np,並輸出版本號。

  1 import numpy as np
  2 print(np.__version__)
  3 #> 1.13.3
參考 View Code

2. 如何創建 1 維數組?

問題:創建數字從 0 到 9 的 1 維數組。

期望輸出:#> array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

  1 import numpy as np
  2 
  3 arr = np.arange(10)
  4 print(arr)
參考 View Code

3. 如何創建 boolean 數組?

問題:創建所有 True 的 3×3 NumPy 數組。

  1 import numpy as np
  2 
  3 ns1 = np.full((3, 3), True, dtype=bool)
  4 #> array([[ True,  True,  True],
  5 #>        [ True,  True,  True],
  6 #>        [ True,  True,  True]], dtype=bool)
  7 print(ns1)
  8 
  9 # Alternate method:
 10 ns = np.ones((3,3), dtype=bool)
 11 print(ns)
 12 
參考 View Code

4. 如何從 1 維數組中提取滿足給定條件的項?

問題:從 arr 中提取所有奇數。

     輸入:  >>arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])`

期望輸出:>>#> array([1, 3, 5, 7, 9])

  1 import numpy as np
  2 
  3 arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  4 ns = arr[arr % 2 == 1]
  5 print(ns)
參考 View Code

5. 如何將 NumPy 數組中滿足給定條件的項替換成另一個數值?

問題:將 arr 中的所有奇數替換成 -1。

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

期望輸出:#> array([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1])

  1 import numpy as np
  2 
  3 arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  4 arr[arr % 2 == 1] = -1
  5 print(arr)
  6 
參考 View Code

6. 如何在不影響原始數組的前提下替換滿足給定條件的項?

問題:將 arr 中所有奇數替換成 -1,且不改變 arr。

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

期望輸出:out#> array([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1])

          arr#> array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

  1 import numpy as np
  2 
  3 arr = np.arange(10)
  4 out = np.where(arr % 2 == 1, -1, arr)
  5 print(arr)
  6 print(out)
參考 View Code

7. 如何重塑(reshape)數組?

問題:將 1 維數組轉換成 2 維數組(兩行)。

     輸入: np.arange(10)

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

期望輸出:#> array([[0, 1, 2, 3, 4],

          #> [5, 6, 7, 8, 9]])

  1 import numpy as np
  2 
  3 arr = np.arange(10)
  4 arr.reshape(2, -1)
  5 print(arr)
參考 View Code

8. 如何垂直堆疊兩個數組?

問題:垂直堆疊數組 a 和 b。

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

期望輸出:#> array([[0, 1, 2, 3, 4],

          #> [5, 6, 7, 8, 9],

          #> [1, 1, 1, 1, 1],

         #> [1, 1, 1, 1, 1]])

  1 import numpy as np
  2 
  3 a = np.arange(10).reshape(2,-1)
  4 b = np.repeat(1, 10).reshape(2,-1)
  5 
  6 r1 = np.concatenate([a, b], axis=0)     # 方法一
  7 r2 = np.vstack([a, b])                  # 方法二
  8 r3 = np.r_[a, b]                        # 方法三
  9 
 10 print(r1)
 11 print(r2)
 12 print(r3)
 13 
參考 View Code

9. 如何水平堆疊兩個數組?

問題:水平堆疊數組 a 和 b。

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

期望輸出:#> array([[0, 1, 2, 3, 4, 1, 1, 1, 1, 1],

          #> [5, 6, 7, 8, 9, 1, 1, 1, 1, 1]])

  1 import numpy as np
  2 
  3 a = np.arange(10).reshape(2,-1)
  4 b = np.repeat(1, 10).reshape(2,-1)
  5 
  6 r1 = np.concatenate([a, b], axis=1)     # 方法一
  7 r2 = np.hstack([a, b])                  # 方法二
  8 r3 = np.c_[a, b]                        # 方法三
  9 print(r1)
 10 print(r2)
 11 print(r3)
參考 View Code

10. 在不使用硬編碼的前提下,如何在 NumPy 中生成自定義序列?

問題:在不使用硬編碼的前提下創建以下模式。僅使用 NumPy 函數和以下輸入數組 a。

      輸入:a = np.array([1,2,3])`

期望輸出:#> array([1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3])

  1 import numpy as np
  2 
  3 a = np.array([1,2,3])
  4 r1 = np.r_[np.repeat(a, 3), np.tile(a, 3)]
  5 print(r1)
參考 View Code

 

11. 如何獲得兩個 Python NumPy 數組中共同的項?

問題:獲取數組 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])

期望輸出:array([2, 4])

  1 import numpy as np
  2 
  3 a = np.array([1,2,3,2,3,4,3,4,5,6])
  4 b = np.array([7,2,10,2,7,4,9,4,9,8])
  5 r1 = np.intersect1d(a,b)
  6 print(r1)
參考 View Code

12. 如何從一個數組中移除與另一個數組重復的項?

問題:從數組 a 中移除出現在數組 b 中的所有項。

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

期望輸出:array([1,2,3,4])

  1 import numpy as np
  2 
  3 a = np.array([1,2,3,4,5])
  4 b = np.array([5,6,7,8,9])
  5 r1 = np.setdiff1d(a,b)
  6 print(r1)
參考 View Code

13. 如何獲取兩個數組匹配元素的位置?

問題:獲取數組 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])

期望輸出:#> (array([1, 3, 5, 7]),)

  1 import numpy as np
  2 
  3 a = np.array([1,2,3,2,3,4,3,4,5,6])
  4 b = np.array([7,2,10,2,7,4,9,4,9,8])
  5 
  6 r1 = np.where(a == b)
  7 print(r1)
參考 View Code

14. 如何從 NumPy 數組中提取給定范圍內的所有數字?

問題:從數組 a 中提取 5 和 10 之間的所有項。

      輸入:a = np.arange(15)

期望輸出:(array([ 5, 6, 7, 8, 9, 10]),)

  1 import numpy as np
  2 
  3 a = np.arange(15)
  4 
  5 index = np.where((a >= 5) & (a <= 10))  # 方法一
  6 r1 = a[index]
  7 
  8 index = np.where(np.logical_and(a >= 5, a <= 10))  # 方法二
  9 r2 = a[index]
 10 
 11 r3 = a[(a >= 5) & (a <= 10)]  # 方法三
 12 print(r1)
 13 print(r2)
 14 print(r3)
 15 
參考 View Code

15. 如何創建一個 Python 函數以對 NumPy 數組執行元素級的操作?

問題:轉換函數 maxx,使其從只能對比標量而變為對比兩個數組。

輸入:

1 def maxx(x, y): 2 """Get the maximum of two items""" 3 if x >= y: 4 return x 5 else: 6 return y 7 8 maxx(1, 5) 9 #> 5

期望輸出:a = np.array([5, 7, 9, 8, 6, 4, 5])

          b = np.array([6, 3, 4, 8, 9, 7, 1])

          pair_max(a, b)

         #> array([ 6., 7., 9., 8., 9., 7., 5.])

  1 import numpy as np
  2 
  3 
  4 def maxx(x, y):
  5     """Get the maximum of two items"""
  6     if x >= y:
  7         return x
  8     else:
  9         return y
 10 
 11 
 12 pair_max = np.vectorize(maxx, otypes=[float])
 13 
 14 a = np.array([5, 7, 9, 8, 6, 4, 5])
 15 b = np.array([6, 3, 4, 8, 9, 7, 1])
 16 
 17 r1 = pair_max(a, b)
 18 print(r1)
參考 View Code

16. 如何在 2d NumPy 數組中交換兩個列?

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

arr = np.arange(9).reshape(3,3)arr

  1 import numpy as np
  2 
  3 arr = np.arange(9).reshape(3,3)
  4 r1 = arr[:, [1,0,2]]
  5 print(r1)
參考 View Code

17. 如何在 2d NumPy 數組中交換兩個行?

問題:在數組 arr 中交換行 1 和行 2。

arr = np.arange(9).reshape(3,3)arr

  1 import numpy as np
  2 
  3 arr = np.arange(9).reshape(3, 3)
  4 r1 = arr[[1, 0, 2], :]
  5 print(r1)
  6 
參考 View Code

18. 如何反轉 2D 數組的所有行?

問題:反轉 2D 數組 arr 中的所有行。

# Inputarr = np.arange(9).reshape(3,3)

  1 import numpy as np
  2 
  3 arr = np.arange(9).reshape(3,3)
  4 r1 = arr[::-1]
  5 print(r1)
參考 View Code

19. 如何反轉 2D 數組的所有列?

問題:反轉 2D 數組 arr 中的所有列。

  • # Inputarr = np.arange(9).reshape(3,3)
  1 import numpy as np
  2 
  3 arr = np.arange(9).reshape(3,3)
  4 r1 = arr[:, ::-1]
  5 print(r1)
參考 View Code

20. 如何創建一個包含 5 和 10 之間隨機浮點的 2 維數組?

問題:創建一個形態為 5×3 的 2 維數組,包含 5 和 10 之間的隨機十進制小數。

  1 import numpy as np
  2 
  3 arr = np.arange(9).reshape(3,3)
  4 # Solution Method 1:
  5 rand_arr = np.random.randint(low=5, high=10, size=(5,3)) + np.random.random((5,3))
  6 print("1",rand_arr)
  7 
  8 # Solution Method 2:
  9 rand_arr = np.random.uniform(5,10, size=(5,3))
 10 print("2",rand_arr)
參考 View Code

21. 如何在 Python NumPy 數組中僅輸出小數點后三位的數字?

問題:輸出或顯示 NumPy 數組 rand_arr 中小數點后三位的數字。

輸入:rand_arr = np.random.random((5,3))

  1 import numpy as np
  2 
  3 rand_arr = np.random.random((5,3))
  4 # Create the random array
  5 rand_arr = np.random.random([5,3])
  6 # Limit to 3 decimal places
  7 np.set_printoptions(precision=3)
  8 rand_arr[:4]
  9 print(rand_arr)
 10 
參考 View Code

22. 如何通過禁用科學計數法(如 1e10)打印 NumPy 數組?

問題:通過禁用科學計數法(如 1e10)打印 NumPy 數組 rand_arr。

輸入# Create the random arraynp.random.seed(100)

      rand_arr = np.random.random([3,3])/1e3rand_arr

期望輸出:#> array([[ 0.000543, 0.000278, 0.000425],

          #> [ 0.000845, 0.000005, 0.000122],

          #> [ 0.000671, 0.000826, 0.000137]])

  1 import numpy as np
  2 
  3 np.set_printoptions(suppress=False)
  4 # Create the random array
  5 np.random.seed(100)
  6 rand_arr = np.random.random([3,3])/1e3
  7 
  8 print(rand_arr)
參考 View Code

23. 如何限制 NumPy 數組輸出中項的數目?

問題:將 Python NumPy 數組 a 輸出的項的數目限制在最多 6 個元素。

      輸入:a = np.arange(15)

期望輸出:#> array([ 0, 1, 2, ..., 12, 13, 14])

  1 mport numpy as np
  2 
  3 np.set_printoptions(threshold=6)
  4 a = np.arange(15)
  5 
  6 print(a)
參考 View Code

24. 如何在不截斷數組的前提下打印出完整的 NumPy 數組?

問題:在不截斷數組的前提下打印出完整的 NumPy 數組 a。

輸入:np.set_printoptions(threshold=6)

      a = np.arange(15)

期望輸出:a#> array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])

25. 如何向 Python NumPy 導入包含數字和文本的數據集,同時保持文本不變?

問題:導入 iris 數據集,保持文本不變。

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris = np.genfromtxt(url, delimiter=',', dtype='object')
  5 names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')
  6 
  7 r1 = iris[:3]	# Print the first 3 rows
  8 print(r1)
參考 View Code

26. 如何從 1 維元組數組中提取特定的列?

問題:從前一個問題導入的 1 維 iris 中提取文本列 species。

輸入:rl = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis_1d = np.genfromtxt(url, delimiter= , , dtype=None)

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris_1d = np.genfromtxt(url, delimiter=',', dtype=None)
  5 print(iris_1d.shape)
  6 
  7 species = np.array([row[4] for row in iris_1d])
  8 r1 = species[:5]
  9 print(r1)
 10 
參考 View Code

27. 如何將 1 維元組數組轉換成 2 維 NumPy 數組?

問題:忽略 species 文本字段,將 1 維 iris 轉換成 2 維數組 iris_2d。

url = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis_1d = np.genfromtxt(url, delimiter= , , dtype=None)

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris_1d = np.genfromtxt(url, delimiter=',', dtype=None)
  5 
  6 iris_2d = np.array([row.tolist()[:4] for row in iris_1d])		#方法一
  7 r1 = iris_2d[:4]
  8 
  9 iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])	#方法二
 10 r2 = iris_2d[:4]
 11 print(r1)
 12 print(r2)
參考 View Code

 

28. 如何計算 NumPy 數組的平均值、中位數和標准差?

問題:找出 iris sepallength(第一列)的平均值、中位數和標准差。

url = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis = np.genfromtxt(url, delimiter= , , dtype= object )

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris = np.genfromtxt(url, delimiter=',', dtype='object')
  5 sepallength = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0])
  6 
  7 mu, med, sd = np.mean(sepallength), np.median(sepallength), np.std(sepallength)
  8 print(mu, med, sd)
參考 View Code

 

29. 如何歸一化數組,使值的范圍在 0 和 1 之間?

問題:創建 iris sepallength 的歸一化格式,使其值在 0 到 1 之間。

輸入:url = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datasepallength = np.genfromtxt(url, delimiter= , , dtype= float , usecols=[0])

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 sepallength = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0])
  5 
  6 Smax, Smin = sepallength.max(), sepallength.min()
  7 S1 = (sepallength - Smin)/(Smax - Smin)
  8 S2 = (sepallength - Smin)/sepallength.ptp()  # Thanks, David Ojeda!
  9 print(S1)
 10 print(S2)
參考 View Code

30. 如何計算 softmax 分數?

問題:計算 sepallength 的 softmax 分數。

url = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datasepallength = np.genfromtxt(url, delimiter= , , dtype= float , usecols=[0])

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris = np.genfromtxt(url, delimiter=',', dtype='object')
  5 sepallength = np.array([float(row[0]) for row in iris])
  6 
  7 def softmax(x):
  8     """Compute softmax values for each sets of scores in x.
  9     https://stackoverflow.com/questions/34968722/how-to-implement-the-softmax-function-in-python"""
 10     e_x = np.exp(x - np.max(x))
 11     return e_x / e_x.sum(axis=0)
 12 
 13 r1 = softmax(sepallength)
 14 print(r1)
 15 
 16 
參考 View Code

31. 如何找到 NumPy 數組的百分數?

問題:找出 iris sepallength(第一列)的第 5 個和第 95 個百分數。

url = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datasepallength = np.genfromtxt(url, delimiter= , , dtype= float , usecols=[0])

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 sepallength = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0])
  5 r1 = np.percentile(sepallength, q=[5, 95])
  6 print(r1)
參考 View Code

32. 如何在數組的隨機位置插入值?

問題:在 iris_2d 數據集中的 20 個隨機位置插入 np.nan 值。

# Inputurl = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis_2d = np.genfromtxt(url, delimiter= , , dtype= object )

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris_2d = np.genfromtxt(url, delimiter=',', dtype='object')
  5 
  6 i, j = np.where(iris_2d)
  7 np.random.seed(100)
  8 iris_2d[np.random.choice((i), 20), np.random.choice((j), 20)] = np.nan
  9 
 10 # Method 2
 11 np.random.seed(100)
 12 iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan
 13 
 14 # Print first 10 rows
 15 print(iris_2d[:10])
參考 View Code

33. 如何在 NumPy 數組中找出缺失值的位置?

問題:在 iris_2d 的 sepallength(第一列)中找出缺失值的數目和位置。

# Inputurl = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis_2d = np.genfromtxt(url, delimiter= , , dtype= float )iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan

  1 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  2 iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])
  3 iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan
  4 
  5 print("Number of missing values: \n", np.isnan(iris_2d[:, 0]).sum())
  6 print("Position of missing values: \n", np.where(np.isnan(iris_2d[:, 0])))
參考 View Code

34. 如何基於兩個或以上條件過濾 NumPy 數組?

問題:過濾 iris_2d 中滿足 petallength(第三列)> 1.5 和 sepallength(第一列)< 5.0 的行。

# Inputurl = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis_2d = np.genfromtxt(url, delimiter= , , dtype= float , usecols=[0,1,2,3])

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])
  5 
  6 condition = (iris_2d[:, 2] > 1.5) & (iris_2d[:, 0] < 5.0)
  7 r1 = iris_2d[condition]
  8 print(r1)
參考 View Code

35. 如何在 NumPy 數組中刪除包含缺失值的行?

問題:選擇 iris_2d 中不包含 nan 值的行。

# Inputurl = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis_2d = np.genfromtxt(url, delimiter= , , dtype= float , usecols=[0,1,2,3])

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])
  5 iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan
  6 
  7 # Method 1:
  8 any_nan_in_row = np.array([~np.any(np.isnan(row)) for row in iris_2d])
  9 r1 = iris_2d[any_nan_in_row][:5]
 10 
 11 # Method 2: (By Rong)
 12 r2 = iris_2d[np.sum(np.isnan(iris_2d), axis = 1) == 0][:5]
 13 print(r1)
 14 print(r2)
參考 View Code

36. 如何找出 NumPy 數組中兩列之間的關聯性?

問題:找出 iris_2d 中 SepalLength(第一列)和 PetalLength(第三列)之間的關聯性。

# Inputurl = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis_2d = np.genfromtxt(url, delimiter= , , dtype= float , usecols=[0,1,2,3])

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])
  5 
  6 r1 = np.corrcoef(iris[:, 0], iris[:, 2])[0, 1]
  7 print(r1)
  8 
參考 View Code

37. 如何確定給定數組是否有空值?

問題:確定 iris_2d 是否有缺失值。

# Inputurl = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis_2d = np.genfromtxt(url, delimiter= , , dtype= float , usecols=[0,1,2,3])

  1 import numpy as np
  2 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  3 iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])
  4 
  5 r1 = np.isnan(iris_2d).any()
  6 print(r1)
參考 View Code

38. 如何在 NumPy 數組中將所有缺失值替換成 0?

問題:在 NumPy 數組中將所有 nan 替換成 0。

# Inputurl = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis_2d = np.genfromtxt(url, delimiter= , , dtype= float , usecols=[0,1,2,3])iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])
  5 iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan
  6 iris_2d[np.isnan(iris_2d)] = 0
  7 r1 = iris_2d[:4]
  8 print(r1)
參考 View Code

 

39. 如何在 NumPy 數組中找出唯一值的數量?

問題:在 iris 的 species 列中找出唯一值及其數量。

# Inputurl = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis = np.genfromtxt(url, delimiter= , , dtype= object )names = ( sepallength , sepalwidth , petallength , petalwidth , species )

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris = np.genfromtxt(url, delimiter=',', dtype='object')
  5 names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')
  6 species = np.array([row.tolist()[4] for row in iris])
  7 r1 = np.unique(species, return_counts=True)
  8 print(r1)
參考 View Code

40. 如何將一個數值轉換為一個類別(文本)數組?

問題:將 iris_2d 的 petallength(第三列)轉換以構建一個文本數組,按如下規則進行轉換:

  • Less than 3 –> ‘small’

  • 3-5 –>  medium

  • >=5 –>  large

  • # Inputurl = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis = np.genfromtxt(url, delimiter= , , dtype= object )names = ( sepallength , sepalwidth , petallength , petalwidth , species )
  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris = np.genfromtxt(url, delimiter=',', dtype='object')
  5 names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')
  6 
  7 petal_length_bin = np.digitize(iris[:, 2].astype('float'), [0, 3, 5, 10])
  8 label_map = {1: 'small', 2: 'medium', 3: 'large', 4: np.nan}
  9 petal_length_cat = [label_map[x] for x in petal_length_bin]
 10 r = petal_length_cat[:4]
 11 print(r)
參考 View Code

41. 如何基於 NumPy 數組現有列創建一個新的列?

問題:為 iris_2d 中的 volume 列創建一個新的列,volume 指 (pi x petallength x sepal_length^2)/3。

url = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis_2d = np.genfromtxt(url, delimiter= , , dtype= object )names = ( sepallength , sepalwidth , petallength , petalwidth , species )

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris_2d = np.genfromtxt(url, delimiter=',', dtype='object')
  5 
  6 sepallength = iris_2d[:, 0].astype('float')
  7 petallength = iris_2d[:, 2].astype('float')
  8 volume = (np.pi * petallength * (sepallength**2))/3
  9 volume = volume[:, np.newaxis]
 10 out = np.hstack([iris_2d, volume])
 11 
 12 r1 = out[:4]
 13 print(r1)
參考 View Code

42. 如何在 NumPy 中執行概率采樣?

問題:隨機采樣 iris 數據集中的 species 列,使得 setose 的數量是 versicolor 和 virginica 數量的兩倍。

# Import iris keeping the text column intacturl = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis = np.genfromtxt(url, delimiter= , , dtype= object )

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris = np.genfromtxt(url, delimiter=',', dtype='object')
  5 
  6 species = iris[:, 4]
  7 np.random.seed(100)
  8 a = np.array(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'])
  9 species_out = np.random.choice(a, 150, p=[0.5, 0.25, 0.25])
 10 np.random.seed(100)
 11 probs = np.r_[np.linspace(0, 0.500, num=50), np.linspace(0.501, .750, num=50), np.linspace(.751, 1.0, num=50)]
 12 index = np.searchsorted(probs, np.random.random(150))
 13 species_out = species[index]
 14 print(np.unique(species_out, return_counts=True))
 15 
參考 View Code

 

43. 如何在多維數組中找到一維的第二最大值?

問題:在 species setosa 的 petallength 列中找到第二最大值。

# Inputurl = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis = np.genfromtxt(url, delimiter= , , dtype= object )names = ( sepallength , sepalwidth , petallength , petalwidth , species )

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris = np.genfromtxt(url, delimiter=',', dtype='object')
  5 
  6 petal_len_setosa = iris[iris[:, 4] == b'Iris-setosa', [2]].astype('float')
  7 
  8 r1 = np.unique(np.sort(petal_len_setosa))[-2]
  9 print(r1)
參考 View Code

44. 如何用給定列將 2 維數組排序?

問題:基於 sepallength 列將 iris 數據集排序。

url = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis = np.genfromtxt(url, delimiter= , , dtype= object )names = ( sepallength , sepalwidth , petallength , petalwidth , species )

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris = np.genfromtxt(url, delimiter=',', dtype='object')
  5 names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')
  6 
  7 print(iris[iris[:,0].argsort()][:20])
參考 View Code

45. 如何在 NumPy 數組中找到最頻繁出現的值?

問題:在 iris 數據集中找到 petallength(第三列)中最頻繁出現的值。

url = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis = np.genfromtxt(url, delimiter= , , dtype= object )names = ( sepallength , sepalwidth , petallength , petalwidth , species )

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris = np.genfromtxt(url, delimiter=',', dtype='object')
  5 vals, counts = np.unique(iris[:, 2], return_counts=True)
  6 print(vals[np.argmax(counts)])
  7 
參考 View Code

 

46. 如何找到第一個大於給定值的數的位置?

問題:在 iris 數據集的 petalwidth(第四列)中找到第一個值大於 1.0 的數的位置。

# Input:url = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis = np.genfromtxt(url, delimiter= , , dtype= object )

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris = np.genfromtxt(url, delimiter=',', dtype='object')
  5 
  6 r1 = np.argwhere(iris[:, 3].astype(float) > 1.0)[0]
  7 print(r1)
參考 View Code

 

47. 如何將數組中所有大於給定值的數替換為給定的 cutoff 值?

問題:對於數組 a,將所有大於 30 的值替換為 30,將所有小於 10 的值替換為 10。

輸入:np.random.seed(100)np.random.uniform(1,50, 20)

  1 import numpy as np
  2 
  3 np.set_printoptions(precision=2)
  4 np.random.seed(100)
  5 a = np.random.uniform(1,50, 20)
  6 
  7 np.clip(a, a_min=10, a_max=30)
  8 
  9 print(np.where(a < 10, 10, np.where(a > 30, 30, a)))
參考 View Code

48. 如何在 NumPy 數組中找到 top-n 數值的位置?

問題:在給定數組 a 中找到 top-5 最大值的位置。

np.random.seed(100)a = np.random.uniform(1,50, 20)

  1 import numpy as np
  2 
  3 np.random.seed(100)
  4 a = np.random.uniform(1,50, 20)
  5 
  6 # Solution:
  7 print(a.argsort())      #> [18 7 3 10 15]
  8 # Solution 2:
  9 print(np.argpartition(-a, 5)[:5])       #> [15 10  3  7 18]
 10 
 11 r1 = a[a.argsort()][-5:]     # Method 1:
 12 print(r1)
 13 
 14 r2 = np.sort(a)[-5:]         # Method 2:
 15 print(r2)
 16 
 17 r3 = np.partition(a, kth=-5)[-5:]        # Method 3:
 18 print(r3)
 19 
 20 r4 = a[np.argpartition(-a, 5)][:5]       # Method 4:
 21 print(r4)
參考 View Code

49. 如何逐行計算數組中所有值的數量?

問題:逐行計算唯一值的數量。

輸入:np.random.seed(100)arr = np.random.randint(1,11,size=(6, 10))

arr> array([[ 9, 9, 4, 8, 8, 1, 5, 3, 6, 3],> [ 3, 3, 2, 1, 9, 5, 1, 10, 7, 3],> [ 5, 2, 6, 4, 5, 5, 4, 8, 2, 2],> [ 8, 8, 1, 3, 10, 10, 4, 3, 6, 9],> [ 2, 1, 8, 7, 3, 1, 9, 3, 6, 2],> [ 9, 2, 6, 5, 3, 9, 4, 6, 1, 10]])

期望輸出:> [[1, 0, 2, 1, 1, 1, 0, 2, 2, 0],> [2, 1, 3, 0, 1, 0, 1, 0, 1, 1],> [0, 3, 0, 2, 3, 1, 0, 1, 0, 0],> [1, 0, 2, 1, 0, 1, 0, 2, 1, 2],> [2, 2, 2, 0, 0, 1, 1, 1, 1, 0],> [1, 1, 1, 1, 1, 2, 0, 0, 2, 1]]

輸出包含 10 個列,表示從 1 到 10 的數字。這些數值分別代表每一行的計數數量。例如,Cell(0,2) 中有值 2,這意味着,數字 3 在第一行出現了兩次。

  1 import numpy as np
  2 
  3 np.random.seed(100)
  4 arr = np.random.randint(1,11,size=(6, 10))
  5 print(arr)
參考 View Code

50. 如何將 array_of_arrays 轉換為平面 1 維數組?

問題:將 array_of_arrays 轉換為平面線性 1 維數組。

# Input:arr1 = np.arange(3)arr2 = np.arange(3,7)arr3 = np.arange(7,10)array_of_arrays = np.array([arr1, arr2, arr3])array_of_arrays#> array([array([0, 1, 2]), array([3, 4, 5, 6]), array([7, 8, 9])], dtype=object)

期望輸出:#> array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

  1 import numpy as np
  2 
  3 arr1 = np.arange(3)
  4 arr2 = np.arange(3,7)
  5 arr3 = np.arange(7,10)
  6 
  7 array_of_arrays = np.array([arr1, arr2, arr3])
  8 print('array_of_arrays: ', array_of_arrays)
  9 
 10 arr_2d = np.array([a for arr in array_of_arrays for a in arr])
 11 
 12 arr_2d = np.concatenate(array_of_arrays)
 13 print(arr_2d)
參考 View Code

51. 如何為 NumPy 數組生成>

問題:計算>

輸入:np.random.seed(101) arr = np.random.randint(1,4, size=6)arr#> array([2, 3, 2, 2, 2, 1])

輸出> array([[ 0., 1., 0.],#> [ 0., 0., 1.],#> [ 0., 1., 0.],#> [ 0., 1., 0.],#> [ 0., 1., 0.],#> [ 1., 0., 0.]])

  1 import numpy as np
  2 
  3 np.random.seed(101)
  4 arr = np.random.randint(1,4, size=6)
  5 print(arr)
  6 #> array([2, 3, 2, 2, 2, 1])
  7 
  8 def one_hot_encodings(arr):
  9     uniqs = np.unique(arr)
 10     out = np.zeros((arr.shape[0], uniqs.shape[0]))
 11     for i, k in enumerate(arr):
 12         out[i, k-1] = 1
 13     return out
 14 
 15 r1 = one_hot_encodings(arr)
 16 print("r1",r1)
 17 r2 = (arr[:, None] == np.unique(arr)).view(np.int8)
 18 print("r2",r2)
參考 View Code

52. 如何創建由類別變量分組確定的一維數值?

問題:創建由類別變量分組的行數。使用以下來自 iris species 的樣本作為輸入。

輸入:url = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.dataspecies = np.genfromtxt(url, delimiter= , , dtype= str , usecols=4)species_small = np.sort(np.random.choice(species, size=20))species_small#> array([ Iris-setosa , Iris-setosa , Iris-setosa , Iris-setosa ,#> Iris-setosa , Iris-setosa , Iris-versicolor , Iris-versicolor ,#> Iris-versicolor , Iris-versicolor , Iris-versicolor ,#> Iris-versicolor , Iris-virginica , Iris-virginica ,#> Iris-virginica , Iris-virginica , Iris-virginica ,#> Iris-virginica , Iris-virginica , Iris-virginica ],#> dtype= <U15 )

期望輸出:#> [0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6, 7]

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 species = np.genfromtxt(url, delimiter=',', dtype='str', usecols=4)
  5 np.random.seed(100)
  6 species_small = np.sort(np.random.choice(species, size=20))
  7 print(species_small)
  8 print([i for val in np.unique(species_small) for i, grp in enumerate(species_small[species_small==val])])
參考 View Code

53. 如何基於給定的類別變量創建分組 id?

問題:基於給定的類別變量創建分組 id。使用以下來自 iris species 的樣本作為輸入。

輸入:url = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.dataspecies = np.genfromtxt(url, delimiter= , , dtype= str , usecols=4)species_small = np.sort(np.random.choice(species, size=20))species_small

#> array([ Iris-setosa , Iris-setosa , Iris-setosa , Iris-setosa ,

#> Iris-setosa , Iris-setosa , Iris-versicolor , Iris-versicolor ,

#> Iris-versicolor , Iris-versicolor , Iris-versicolor ,

#> Iris-versicolor , Iris-virginica , Iris-virginica ,

#> Iris-virginica , Iris-virginica , Iris-virginica ,

#> Iris-virginica , Iris-virginica , Iris-virginica ],

#> dtype= <U15 )

期望輸出:#> [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 species = np.genfromtxt(url, delimiter=',', dtype='str', usecols=4)
  5 np.random.seed(100)
  6 species_small = np.sort(np.random.choice(species, size=20))
  7 print(species_small)
  8 
  9 output = [np.argwhere(np.unique(species_small) == s).tolist()[0][0] for val in np.unique(species_small) for s in species_small[species_small==val]]
 10 
 11 # Solution: For Loop version
 12 output = []
 13 uniqs = np.unique(species_small)
 14 
 15 for val in uniqs:  # uniq values in group
 16     for s in species_small[species_small==val]:  # each element in group
 17         groupid = np.argwhere(uniqs == s).tolist()[0][0]  # groupid
 18         output.append(groupid)
 19 
 20 print(output)
參考 View Code

54. 如何使用 NumPy 對數組中的項進行排序?

問題:為給定的數值數組 a 創建排序。

輸入:np.random.seed(10)a = np.random.randint(20, size=10)print(a)#> [ 9 4 15 0 17 16 17 8 9 0]

期望輸出:[4 2 6 0 8 7 9 3 5 1]

  1 import numpy as np
  2 
  3 np.random.seed(10)
  4 a = np.random.randint(20, size=10)
  5 print('Array: ', a)
  6 
  7 print(a.argsort().argsort())
  8 print('Array: ', a)
參考 View Code

55. 如何使用 NumPy 對多維數組中的項進行排序?

問題:給出一個數值數組 a,創建一個形態相同的排序數組。

輸入:np.random.seed(10)a = np.random.randint(20, size=[2,5])print(a)#> [[ 9 4 15 0 17]#> [16 17 8 9 0]]

期望輸出:#> [[4 2 6 0 8]#> [7 9 3 5 1]]

  1 import numpy as np
  2 
  3 np.random.seed(10)
  4 a = np.random.randint(20, size=[2,5])
  5 print(a)
  6 
  7 print(a.ravel().argsort().argsort().reshape(a.shape))
參考 View Code

56. 如何在 2 維 NumPy 數組中找到每一行的最大值?

問題:在給定數組中找到每一行的最大值。

np.random.seed(100)a = np.random.randint(1,10, [5,3])a#> array([[9, 9, 4],#> [8, 8, 1],

#> [5, 3, 6],#> [3, 3, 3],#> [2, 1, 9]])

  1 import numpy as np
  2 
  3 np.random.seed(100)
  4 a = np.random.randint(1,10, [5,3])
  5 print("a=",a)
  6 
  7 r1 = np.amax(a, axis=1)
  8 print("r1=",r1)
  9 r2 = np.apply_along_axis(np.max, arr=a, axis=1)
 10 print("r2",r2)
 11 
參考 View Code

57. 如何計算 2 維 NumPy 數組每一行的 min-by-max?

問題:給定一個 2 維 NumPy 數組,計算每一行的 min-by-max。

np.random.seed(100)a = np.random.randint(1,10, [5,3])a#> array([[9, 9, 4],#> [8, 8, 1],#> [5, 3, 6],#> [3, 3, 3],#> [2, 1, 9]])

  1 import numpy as np
  2 
  3 np.random.seed(100)
  4 a = np.random.randint(1,10, [5,3])
  5 print("a=",a)
  6 
  7 
  8 r1 = np.apply_along_axis(lambda x: np.min(x)/np.max(x), arr=a, axis=1)
  9 print("r1",r1)
 10 
參考 View Code

58. 如何在 NumPy 數組中找到重復條目?

問題:在給定的 NumPy 數組中找到重復條目(從第二次出現開始),並將其標記為 True。第一次出現的條目需要標記為 False。

# Inputnp.random.seed(100)a = np.random.randint(0, 5, 10)print( Array: , a)#> Array: [0 0 3 0 2 4 2 2 2 2]

期望輸出:#> [False True False True False False True True True True]

  1 import numpy as np
  2 
  3 np.random.seed(100)
  4 a = np.random.randint(0, 5, 10)
  5 out = np.full(a.shape[0], True)
  6 unique_positions = np.unique(a, return_index=True)[1]
  7 out[unique_positions] = False
  8 
  9 print(out)
參考 View Code

59. 如何找到 NumPy 的分組平均值?

問題:在 2 維 NumPy 數組的類別列中找到數值的平均值。

輸入url = https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.datairis = np.genfromtxt(url, delimiter= , , dtype= object )names = ( sepallength , sepalwidth , petallength , petalwidth , species )

期望解:#> [[b Iris-setosa , 3.418],#> [b Iris-versicolor , 2.770],#> [b Iris-virginica , 2.974]]

  1 import numpy as np
  2 
  3 url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
  4 iris = np.genfromtxt(url, delimiter=',', dtype='object')
  5 names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')
  6 
  7 numeric_column = iris[:, 1].astype('float')  # sepalwidth
  8 grouping_column = iris[:, 4]  # species
  9 
 10 
 11 [[group_val, numeric_column[grouping_column==group_val].mean()] for group_val in np.unique(grouping_column)]
 12 
 13 output = []
 14 for group_val in np.unique(grouping_column):
 15     output.append([group_val, numeric_column[grouping_column==group_val].mean()])
 16 
 17 r1 = output
 18 print(r1)
參考 View Code

60. 如何將 PIL 圖像轉換成 NumPy 數組?

問題:從以下 URL 中導入圖像,並將其轉換成 NumPy 數組。

URL = https://upload.wikimedia.org/wikipedia/commons/8/8b/Denali_Mt_McKinley.jpg

  1 import numpy as np
  2 from io import BytesIO
  3 from PIL import Image
  4 import PIL, requests
  5 
  6 # Import image from URL
  7 URL = 'https://upload.wikimedia.org/wikipedia/commons/8/8b/Denali_Mt_McKinley.jpg'
  8 response = requests.get(URL)
  9 
 10 I = Image.open(BytesIO(response.content))       # Read it as Image
 11 I = I.resize([150,150])     # Optionally resize
 12 arr = np.asarray(I)     # Convert to numpy array
 13 
 14 # Optionaly Convert it back to an image and show
 15 im = PIL.Image.fromarray(np.uint8(arr))
 16 r1 = Image.Image.show(im)
 17 print(r1)
 18 
參考 View Code

61. 如何刪除 NumPy 數組中所有的缺失值?

問題:從 1 維 NumPy 數組中刪除所有的 nan 值。

輸入:np.array([1,2,3,np.nan,5,6,7,np.nan])

期望輸出:array([ 1., 2., 3., 5., 6., 7.])

  1 import numpy as np
  2 
  3 a = np.array([1, 2, 3, np.nan, 5, 6, 7, np.nan])
  4 r1 = a[~np.isnan(a)]
  5 print(r1)
  6 
參考 View Code

62. 如何計算兩個數組之間的歐幾里得距離?

問題:計算兩個數組 a 和 b 之間的歐幾里得距離。

輸入:a = np.array([1,2,3,4,5])b = np.array([4,5,6,7,8])

  1 import numpy as np
  2 
  3 a = np.array([1,2,3,4,5])
  4 b = np.array([4,5,6,7,8])
  5 dist = np.linalg.norm(a-b)
  6 print(dist)
參考 View Code

63. 如何在一個 1 維數組中找到所有的局部極大值(peak)?

問題:在 1 維數組 a 中找到所有的 peak,peak 指一個數字比兩側的數字都大。

輸入:a = np.array([1, 3, 7, 1, 2, 6, 0, 1])

期望輸出:#> array([2, 5])

  1 import numpy as np
  2 
  3 a = np.array([1, 3, 7, 1, 2, 6, 0, 1])
  4 doublediff = np.diff(np.sign(np.diff(a)))
  5 peak_locations = np.where(doublediff == -2)[0] + 1
  6 print(peak_locations)
參考 View Code

64. 如何從 2 維數組中減去 1 維數組,從 2 維數組的每一行分別減去 1 維數組的每一項?

問題:從 2 維數組 a_2d 中減去 1 維數組 b_1d,即從 a_2d 的每一行分別減去 b_1d 的每一項。

輸入:a_2d = np.array([[3,3,3],[4,4,4],[5,5,5]])b_1d = np.array([1,1,1]

期望輸出:#> [[2 2 2]#> [2 2 2]#> [2 2 2]]

  1 import numpy as np
  2 
  3 a_2d = np.array([[3,3,3],[4,4,4],[5,5,5]])
  4 b_1d = np.array([1,2,3])
  5 
  6 print(a_2d - b_1d[:,None])
參考 View Code

65. 如何在數組中找出某個項的第 n 個重復索引?

問題:找到數組 x 中數字 1 的第 5 個重復索引。

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

  1 import numpy as np
  2 
  3 x = np.array([1, 2, 1, 1, 3, 4, 3, 1, 1, 2, 1, 1, 2])
  4 n = 5
  5 
  6 [i for i, v in enumerate(x) if v == 1][n-1]
  7 r1 = np.where(x == 1)[0][n-1]
  8 print(r1)
參考 View Code

66. 如何將 NumPy 的 datetime64 對象(object)轉換為 datetime 的 datetime 對象?

問題:將 NumPy 的 datetime64 對象(object)轉換為 datetime 的 datetime 對象。

Input: a numpy datetime64 objectdt64 = np.datetime64( 2018-02-25 22:10:10 )

  1 import numpy as np
  2 
  3 dt64 = np.datetime64('2018-02-25 22:10:10')
  4 
  5 from datetime import datetime
  6 r1 = dt64.tolist()
  7 print(r1)
  8 
  9 r2 = dt64.astype(datetime)
 10 print(r2)
參考 View Code

67. 如何計算 NumPy 數組的移動平均數?

問題:給定 1 維數組,計算 window size 為 3 的移動平均數。

輸入:np.random.seed(100)Z = np.random.randint(10, size=10)

  1 import numpy as np
  2 
  3 def moving_average(a, n=3):
  4     ret = np.cumsum(a, dtype=float)
  5     ret[n:] = ret[n:] - ret[:-n]
  6     return ret[n - 1:] / n
  7 
  8 np.random.seed(100)
  9 Z = np.random.randint(10, size=10)
 10 print('array: ', Z)
 11 
 12 r1 = moving_average(Z, n=3).round(2)
 13 print("r1=", r1)
 14 
 15 r2 = np.convolve(Z, np.ones(3) / 3, mode='valid')
 16 print("r2=", r2)
 17 
參考 View Code

68. 給定起始數字、length 和步長,如何創建一個 NumPy 數組序列?

問題:從 5 開始,創建一個 length 為 10 的 NumPy 數組,相鄰數字的差是 3。

  1 import numpy as np
  2 
  3 length = 10
  4 start = 5
  5 step = 3
  6 
  7 def seq(start, length, step):
  8     end = start + (step*length)
  9     return np.arange(start, end, step)
 10 
 11 r1 = seq(start, length, step)
 12 print(r1)
參考 View Code

69. 如何在不規則 NumPy 日期序列中填充缺失日期?

問題:給定一個非連續日期序列的數組,通過填充缺失的日期,使其變成連續的日期序列。

輸入# Inputdates = np.arange(np.datetime64( 2018-02-01 ), np.datetime64( 2018-02-25 ), 2)print(dates)

#> [ 2018-02-01 2018-02-03 2018-02-05 2018-02-07 2018-02-09#> 2018-02-11 2018-02-13 2018-02-15 2018-02-17 2018-02-19#> 2018-02-21 2018-02-23 ]

  1 import numpy as np
  2 
  3 dates = np.arange(np.datetime64('2018-02-01'), np.datetime64('2018-02-25'), 2)
  4 print("dates=", dates)
  5 
  6 filled_in = np.array([np.arange(date, (date+d)) for date, d in zip(dates, np.diff(dates))]).reshape(-1)
  7 
  8 output = np.hstack([filled_in, dates[-1]])      # add the last day
  9 print("output=", output)
 10 
 11 out = []
 12 for date, d in zip(dates, np.diff(dates)):
 13     out.append(np.arange(date, (date+d)))
 14 
 15 filled_in = np.array(out).reshape(-1)
 16 output = np.hstack([filled_in, dates[-1]])      # add the last day
 17 print("output", output)
 18 
 19 
參考 View Code

70. 如何基於給定的 1 維數組創建 strides?

問題:給定 1 維數組 arr,使用 strides 生成一個 2 維矩陣,其中 window length 等於 4,strides 等於 2,例如 [[0,1,2,3], [2,3,4,5], [4,5,6,7]..]。

輸入:arr = np.arange(15) arr#> array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])

期望輸出:#> [[ 0 1 2 3]#> [ 2 3 4 5]#> [ 4 5 6 7]#> [ 6 7 8 9]#> [ 8 9 10 11]#> [10 11 12 13]]

  1 import numpy as np
  2 
  3 
  4 def gen_strides(a, stride_len=5, window_len=5):
  5     n_strides = ((a.size - window_len) // stride_len) + 1
  6     return np.array([a[s:(s + window_len)] for s in np.arange(0, n_strides * stride_len, stride_len)])
  7 
  8 print(gen_strides(np.arange(15), stride_len=2, window_len=4))
參考 View Code

 

 歸類 : 面試題收集&整理


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM