一、常規計數
在數據分析和科學計算時,經常需要進行計數操作。使用numpy中的count_nonzero函數可以方便地對數組中的非零元素進行計數。
import numpy as np # 生成數組 arr = np.array([[1, 2, 3], [0, 4, 5], [6, 0, 8]]) # 計算非零元素個數 count = np.count_nonzero(arr) print(count) # 輸出:7
count_nonzero函數還支持在某個軸上進行計數,如在行上計數:
# 對行進行計數 count_row = np.count_nonzero(arr, axis=1) print(count_row) # 輸出:[3 2 2]
二、統計計數
在數據分析中,經常需要進行統計計數,比如統計一組數中每個數字出現的次數,可以使用numpy中的unique函數和bincount函數實現。
使用unique函數可以找到數組中的唯一值,然後使用bincount函數進行計數:
# 生成隨機數組 arr = np.random.randint(low=1, high=6, size=10) print(arr) # 輸出:[2 2 1 2 5 2 1 4 2 3] # 統計每個數字出現的次數 unique, counts = np.unique(arr, return_counts=True) counts_each_num = np.zeros(6, dtype=int) counts_each_num[unique] = counts print(counts_each_num) # 輸出:[0 2 5 1 1 1]
如果需要快速統計一組數中每個數字出現的次數,可以使用numpy中的bincount函數:
# 使用bincount函數統計每個數字出現的次數 counts_each_num = np.bincount(arr) print(counts_each_num) # 輸出:[0 2 5 1 1 1]
三、條件計數
在進行數據篩選時,經常需要對符合條件的數據進行計數。可以使用numpy中的where函數和count_nonzero函數實現條件計數。
如統計數組中大於3的元素個數:
# 使用where函數找到大於3的元素的索引 idx = np.where(arr > 3) # 使用count_nonzero函數計算元素個數 count = np.count_nonzero(arr[idx]) print(count) # 輸出:2
四、行列互換計數
在進行數據分析時,經常需要對矩陣進行行列互換,並對新矩陣進行計數。可以使用numpy中的transpose函數和count_nonzero函數實現。
例如,對下面的矩陣進行行列互換,然後計算非零元素的個數:
# 生成2*3的矩陣 arr = np.array([[0, 1, 2], [3, 4, 5]]) # 對矩陣進行行列互換 new_arr = np.transpose(arr) # 計算非零元素個數 count = np.count_nonzero(new_arr) print(count) # 輸出:6
五、多維計數
在進行多維數據分析時,經常需要進行多維計數操作。numpy中提供了ravel函數可以將多維數組展平為一維,然後進行計數。同時也可以在指定軸上進行計數。
例如,對3維矩陣進行計數:
# 生成3維矩陣 arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) # 將3維矩陣展平為一維,然後進行計數 count = np.count_nonzero(np.ravel(arr)) print(count) # 輸出:8 # 在指定軸(第2個軸)上進行計數 count_axis = np.count_nonzero(arr, axis=1) print(count_axis) # 輸出:[[2 2] [2 2]]
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/238877.html