NumPy - 結構化陣列



NumPy中的結構化陣列

NumPy中的結構化陣列是一個數組,其中每個元素都是複合資料型別。這種複合資料型別可以包含多個欄位,每個欄位都有自己的資料型別,類似於表或記錄。

例如,您可以擁有一個數組,其中每個元素都同時包含姓名(作為字串)和年齡(作為整數)。這有助於您更靈活地處理複雜資料,因為您可以分別訪問和操作每個欄位。

建立結構化陣列

建立結構化陣列的第一步是定義資料型別 (dtype),它指定每個元素的結構。**dtype** 定義為元組列表或字典,其中每個元組或字典條目定義一個欄位名及其資料型別。

以下是結構化陣列中可用的資料型別:

  • **'U10':** 長度為 10 的 Unicode 字串
  • **'i4':** 4 位元組整數
  • **'f8':** 8 位元組浮點數
  • **'b':** 布林值

使用元組列表

您可以使用元組列表定義 dtype 並建立結構化陣列,其中每個元組表示一個欄位。每個元組包含兩個元素:第一個元素是欄位名,第二個元素是該欄位的資料型別。

示例

在下面的示例中,我們使用指定的 dtype 定義了一個包含“name”、“age”和“height”欄位的結構化陣列。然後我們用相應的資料建立這個陣列。

import numpy as np

# Define the dtype
dtype = [('name', 'U10'), ('age', 'i4'), ('height', 'f4')]

# Define the data
data = [('Alice', 30, 5.6), ('Bob', 25, 5.8), ('Charlie', 35, 5.9)]

# Create the structured array
structured_array = np.array(data, dtype=dtype)

print("Structured Array:\n", structured_array)

以下是獲得的輸出:

Structured Array:
[('Alice', 30, 5.6) ('Bob', 25, 5.8) ('Charlie', 35, 5.9)]

使用字典

或者,您可以使用字典定義資料和 dtype,以清晰地指定欄位的名稱和型別。字典中的每個鍵代表一個欄位名,與每個鍵關聯的值定義該欄位的資料型別。

示例

在這個例子中,我們使用字典格式定義結構化陣列的 dtype,以指定“name”、“age”和“height”欄位。然後我們建立並顯示這個結構化陣列及其相應的資料,將其組織成支援每個記錄中多種資料型別的格式。

import numpy as np

# Define the dtype using a dictionary
dtype = np.dtype([('name', 'U10'), ('age', 'i4'), ('height', 'f4')])

# Define the data
data = [('Alice', 30, 5.6), ('Bob', 25, 5.8), ('Charlie', 35, 5.9)]

# Create the structured array
structured_array = np.array(data, dtype=dtype)

print("Structured Array from Dictionary:\n", structured_array)

這將產生以下結果:

Structured Array from Dictionary:
[('Alice', 30, 5.6) ('Bob', 25, 5.8) ('Charlie', 35, 5.9)]

訪問結構化陣列中的欄位

您可以使用欄位名訪問結構化陣列中的各個欄位。這可以透過使用欄位名作為字串來索引陣列來完成。

示例:訪問單個欄位

在下面的示例中,我們定義了一個包含 'name'、'age' 和 'height' 欄位的結構化陣列,然後分別訪問這些欄位。

import numpy as np

# Define a dtype and data for a structured array
dtype = [('name', 'U10'), ('age', 'i4'), ('height', 'f4')]
data = [('Alice', 30, 5.6), ('Bob', 25, 5.8), ('Charlie', 35, 5.9)]
structured_array = np.array(data, dtype=dtype)

# Access the 'name' field
names = structured_array['name']
print("Names:", names)

# Access the 'age' field
ages = structured_array['age']
print("Ages:", ages)

# Access the 'height' field
heights = structured_array['height']
print("Heights:", heights)

以下是上述程式碼的輸出:

Names: ['Alice' 'Bob' 'Charlie']
Ages: [30 25 35]
Heights: [5.6 5.8 5.9]

示例:訪問行

您可以使用索引訪問結構化陣列的特定行。這允許您檢索完整的記錄。在這裡,我們檢索結構化陣列的第一行和第二行。

import numpy as np

# Define a dtype and data for a structured array
dtype = [('name', 'U10'), ('age', 'i4'), ('height', 'f4')]
data = [('Alice', 30, 5.6), ('Bob', 25, 5.8), ('Charlie', 35, 5.9)]
structured_array = np.array(data, dtype=dtype)

# Access the first row
first_row = structured_array[0]
print("First Row:", first_row)

# Access the second row
second_row = structured_array[1]
print("Second Row:", second_row)

以下是上述程式碼的輸出:

First Row: ('Alice', 30, 5.6)
Second Row: ('Bob', 25, 5.8)

修改結構化陣列的欄位

您可以透過索引並將新值賦給它們來修改結構化陣列中各個欄位的值。

要向結構化陣列新增新欄位,您可以結合使用 np.concatenate() 函式和建立一個包含附加欄位的新 dtype。

NumPy 不支援直接向現有的結構化陣列新增欄位。

示例:更新欄位

在下面的示例中,我們透過直接賦值來更新結構化陣列中第一條記錄的 'age' 欄位。

import numpy as np

# Define a dtype and data for a structured array
dtype = [('name', 'U10'), ('age', 'i4'), ('height', 'f4')]
data = [('Alice', 30, 5.6), ('Bob', 25, 5.8), ('Charlie', 35, 5.9)]
structured_array = np.array(data, dtype=dtype)

# Update the 'age' of the first record
structured_array[0]['age'] = 31
print("Updated Structured Array:\n", structured_array)

獲得的輸出如下所示:

Updated Structured Array:
[('Alice', 31, 5.6) ('Bob', 25, 5.8) ('Charlie', 35, 5.9)]

示例:新增新欄位

在這裡,我們透過向其 dtype 新增一個新欄位 'weight' 並更新資料以包含此欄位來擴充套件結構化陣列。

import numpy as np

# Define a dtype and data for the original structured array
dtype = [('name', 'U10'), ('age', 'i4'), ('height', 'f4')]
data = [('Alice', 30, 5.6), ('Bob', 25, 5.8), ('Charlie', 35, 5.9)]
structured_array = np.array(data, dtype=dtype)

# Define a new dtype with an additional field 'weight'
new_dtype = [('name', 'U10'), ('age', 'i4'), ('height', 'f4'), ('weight', 'f4')]

# Define new data including the additional field
new_data = [('Alice', 30, 5.6, 55.0), ('Bob', 25, 5.8, 70.0), ('Charlie', 35, 5.9, 80.0)]

# Create a new structured array with the additional field
new_structured_array = np.array(new_data, dtype=new_dtype)
print("New Structured Array with Additional Field:\n", new_structured_array)

執行上述程式碼後,我們將獲得以下輸出:

New Structured Array with Additional Field:
 [('Alice', 30, 5.6, 55.) ('Bob', 25, 5.8, 70.) ('Charlie', 35, 5.9, 80.)]

排序結構化陣列

對 NumPy 中的結構化陣列進行排序意味著根據一個或多個欄位的值來排列陣列的元素。

由於結構化陣列具有多個欄位,因此排序可以基於這些欄位中的值。例如,您可以根據年齡或身高對人員陣列進行排序。

示例

在下面的示例中,我們透過首先獲得將年齡按升序排列的索引來根據 'age' 欄位對結構化陣列進行排序。然後,我們使用這些索引重新排序整個陣列。

import numpy as np

# Define a structured array
dtype = [('name', 'U10'), ('age', 'i4')]
data = [('Alice', 30), ('Bob', 25), ('Charlie', 35)]
structured_array = np.array(data, dtype=dtype)

# Sort the array by 'age'
sorted_indices = np.argsort(structured_array['age'])
sorted_array = structured_array[sorted_indices]
print("Sorted by Age:\n", sorted_array)

產生的結果如下:

Sorted by Age:
[('Bob', 25) ('Alice', 30) ('Charlie', 35)]

過濾結構化陣列

過濾結構化陣列涉及對一個或多個欄位應用條件並檢索滿足這些條件的元素。

當您想要檢索滿足特定條件的記錄時,這非常有用,例如提取特定欄位超過閾值或與特定值匹配的所有條目。

示例

在這個例子中,我們過濾結構化陣列,只包含 'age' 欄位大於 30 的記錄。

import numpy as np

# Define a structured array
dtype = [('name', 'U10'), ('age', 'i4')]
data = [('Alice', 30), ('Bob', 25), ('Charlie', 35)]
structured_array = np.array(data, dtype=dtype)

# Filter array for ages greater than 30
filtered_array = structured_array[structured_array['age'] > 30]
print("Filtered Array (Age > 30):\n", filtered_array)

我們得到如下所示的輸出:

Filtered Array (Age > 30):[('Charlie', 35)]

組合結構化陣列

組合結構化陣列涉及合併或連線具有已定義 dtype 和命名欄位的陣列。在 NumPy 中,這可以使用 np.concatenate() 函式完成。

示例

在下面的示例中,我們使用 np.concatenate() 函式將兩個具有相同 dtype 的結構化陣列組合成一個數組。

import numpy as np

# Define two structured arrays
dtype = [('name', 'U10'), ('age', 'i4')]
data1 = [('Alice', 30), ('Bob', 25)]
data2 = [('Charlie', 35), ('Dave', 40)]
structured_array1 = np.array(data1, dtype=dtype)
structured_array2 = np.array(data2, dtype=dtype)

# Combine the arrays
combined_array = np.concatenate((structured_array1, structured_array2))
print("Combined Structured Array:\n", combined_array)

這將產生一個新的結構化陣列,其中包含兩個原始陣列中的所有記錄,如下所示:

Combined Structured Array:
[('Alice', 30) ('Bob', 25) ('Charlie', 35) ('Dave', 40)]
廣告