計算扁平化 NumPy 陣列的中位數


中位數

中位數是表示排序後的數值列表中中間值的集中趨勢的統計度量。換句話說,我們可以說中位數是將資料集的上半部分與下半部分分隔開的值。

當元素總數為奇數時,計算中位數的數學公式如下。

Median = (n+1)/2

其中,n 是給定集合中的最後一個元素。

扁平化陣列

扁平化是一個降低陣列維度的過程。扁平化陣列是一個透過扁平化多維陣列建立的**一維**陣列,其中陣列中的所有元素都將連線到一個單行中。

在 NumPy 中,我們有兩個函式**ravel()** 和 **flatten()** 用於扁平化陣列。任何提到的方法都可以用於扁平化給定的多維陣列。

語法

類似地,我們可以使用 median() 函式計算陣列的中位數。

array.flatten()
np.median(flatten_array)

其中,

  • **NumPy** 是庫的名稱

  • **flatten** 是用於扁平化給定陣列的函式

  • **array** 是輸入陣列

  • **median** 是用於查詢給定陣列的中位數的函式

  • **flatten_array** 是儲存扁平化陣列的變數

示例

為了計算陣列的中位數,首先,我們應該使用 flatten() 函式將其扁平化,並將生成的扁平化陣列值作為引數傳遞給 median() 函式,如下例所示 -

import numpy as np
a = np.array([[[34,23],[90,34]],[[43,23],[10,34]]])
print("The input array:",a)
flattened_array = a.flatten()
print("The flattened array of the given array:",flattened_array)
med = np.median(flattened_array)
print("The median of the given flattened array:",med)

輸出

以下是為扁平化陣列計算的中位數的輸出。

The input array: [[[34 23]
  [90 34]]

 [[43 23]
  [10 34]]]
The flattened array of the given array: [34 23 90 34 43 23 10 34]
The median of the given flattened array: 34.0

示例

讓我們再看一個示例,我們嘗試計算 3D 陣列的中位數 -

import numpy as np
a = np.array([[[23,43],[45,56]],[[24,22],[56,78]]])
print("The input array:",a)
flattened_array = a.flatten()
print("The flattened array of the given 3-d array:",flattened_array)
med = np.median(flattened_array)
print("The median of the given flattened array:",med)

輸出

The input array: [[[23 43]
[45 56]]
[[24 22]
[56 78]]]
The flattened array of the given 3-d array: [23 43 45 56 24 22 56 78]
The median of the given flattened array: 44.0

示例

這是另一個查詢 5D 扁平化陣列的中位數的示例。

import numpy as np
a = np.array([[[23,43],[45,56]],[[24,22],[56,78]]],ndmin = 5)
print("The input array:",a)
print("The dimension of the array:",np.ndim(a))
flattened_array = a.flatten()
print("The flattened array of the given 3-d array:",flattened_array)
med = np.median(flattened_array)
print("The median of the given flattened array:",med)

輸出

The input array: [[[[[23 43]
[45 56]]
[[24 22]
[56 78]]]]]
The dimension of the array: 5
The flattened array of the given 3-d array: [23 43 45 56 24 22 56 78]
The median of the given flattened array: 44.0

更新於: 2023年8月7日

80 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.