NumPy - 結構化陣列的操作



在 NumPy 中操作結構化陣列

在 NumPy 中操作結構化陣列意味著根據您的需求修改、重新排列或處理這些陣列中的資料。

結構化陣列是特殊的陣列,其中每個元素可以具有多個欄位(例如姓名、年齡、身高),並且每個欄位可以具有不同的資料型別(例如字串、整數或浮點數)。

在 NumPy 中,您可以透過多種方式操作結構化陣列:

  • 訪問和修改欄位
  • 新增新欄位
  • 刪除欄位
  • 陣列排序
  • 陣列過濾
  • 數組合並
  • 陣列重塑
  • 陣列分割

訪問和修改欄位

您可以使用欄位名稱作為訪問結構化陣列中的特定欄位。這類似於訪問字典中的值的方式。例如,如果您有一個具有姓名、年齡和身高等欄位的結構化陣列,您可以訪問年齡欄位以檢索陣列中儲存的所有年齡。

訪問欄位後,您還可以修改其值。例如,如果您想更新陣列中某人的年齡,您可以透過直接為年齡欄位中相應的元素賦值新值來實現。

示例

在下面的示例中,我們訪問並修改結構化陣列中的“年齡”欄位。具體來說,我們將第一個元素(Alice)的年齡從 30 更新為 31,然後檢索更新後的年齡:

import numpy as np

# Define the dtype with field names and data types
dtype = [('name', 'U10'), ('age', 'i4'), ('height', 'f4')]

# Create the structured array with some initial data
data = [('Alice', 30, 5.6), ('Bob', 25, 5.8), ('Charlie', 35, 5.9)]
structured_array = np.array(data, dtype=dtype)

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

# Modifying the 'age' field - let's update Alice's age to 31
structured_array['age'][0] = 31

# Accessing the 'age' field again to see the changes
print("Ages after modification:", structured_array['age'])

以下是獲得的輸出:

Ages before modification: [30 25 35]
Ages after modification: [31 25 35]

向結構化陣列新增新欄位

要向現有結構化陣列新增新欄位,您需要建立一個包含附加欄位的新陣列並將現有資料複製過去。

當您的資料結構發生變化並需要附加資訊時,此過程可能很有必要。

示例

在這個例子中,我們透過新增一個名為“Grade”的新欄位來擴充套件現有的結構化陣列。我們將現有資料複製到包含附加欄位的新陣列中,然後用相應的值填充新的“Grade”欄位:

import numpy as np

# Existing structured array
students = np.array([(1, 'Alice', 25), (2, 'Bob', 23), (3, 'Charlie', 35)],
                    dtype=[('ID', 'i4'), ('Name', 'U10'), ('Age', 'i4')])

# Define a new dtype with an additional field 'Grade'
new_dtype = [('ID', 'i4'), ('Name', 'U10'), ('Age', 'i4'), ('Grade', 'f4')]

# Create a new structured array with the new dtype
students_with_grade = np.zeros(students.shape, dtype=new_dtype)

# Copy the old data
for field in students.dtype.names:
    students_with_grade[field] = students[field]

# Add data to the new 'Grade' field
students_with_grade['Grade'] = [85.5, 90.0, 88.0]

print(students_with_grade)

這將產生以下結果:

[(1, 'Alice', 25, 85.5) (2, 'Bob', 23, 90. ) (3, 'Charlie', 35, 88. )]

從結構化陣列中刪除欄位

要刪除欄位,您必須建立一個具有修改後的dtype的新結構化陣列,該陣列排除了不需要的欄位,然後將資料從原始陣列複製到新陣列。

示例

在下面的示例中,我們透過建立一個具有簡化 dtype 的新陣列來從現有結構化陣列中刪除“Age”欄位。然後,我們將原始陣列中的相關欄位複製到新陣列中:

import numpy as np

# Original structured array
students = np.array([(1, 'Alice', 25), (2, 'Bob', 23), (3, 'Charlie', 35)],
                    dtype=[('ID', 'i4'), ('Name', 'U10'), ('Age', 'i4')])

# Define a new dtype without the 'Age' field
reduced_dtype = [('ID', 'i4'), ('Name', 'U10')]

# Create a new structured array with the reduced dtype
students_without_age = np.zeros(students.shape, dtype=reduced_dtype)

# Copy the relevant fields
for field in students_without_age.dtype.names:
    students_without_age[field] = students[field]

# Verify the result
print(students_without_age)

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

[(1, 'Alice') (2, 'Bob') (3, 'Charlie')]

結構化陣列排序

NumPy 中的結構化陣列排序涉及根據一個或多個欄位(列)對陣列的元素(行)進行排序。

結構化陣列可以具有不同資料型別的多個欄位(例如,整數、浮點數、字串),排序允許您以有意義的方式組織資料,例如按年齡、名稱或任何其他屬性排列記錄。

示例

在下面的示例中,我們使用帶有“order”引數的 np.sort() 函式根據“Age”欄位對結構化陣列進行排序。這會根據“Age”值按升序重新排列記錄:

import numpy as np

# Original structured array
students = np.array([(1, 'Alice', 25), (2, 'Bob', 23), (3, 'Charlie', 35)],
                    dtype=[('ID', 'i4'), ('Name', 'U10'), ('Age', 'i4')])

# Sort by 'Age'
sorted_students = np.sort(students, order='Age')
print(sorted_students)

獲得的輸出如下所示:

[(2, 'Bob', 23) (1, 'Alice', 25) (3, 'Charlie', 35)]

過濾結構化陣列中的資料

使用 NumPy 過濾結構化陣列中的資料涉及選擇滿足特定條件的資料子集。

要過濾結構化陣列,您可以使用布林索引。這涉及根據應用於一個或多個欄位的條件建立一個布林掩碼(一個包含 True 和 False 值的陣列)。然後,您可以使用此掩碼索引到原始陣列並提取所需記錄的子集。

示例

在這個例子中,我們使用布林掩碼來過濾結構化陣列,只選擇“Age”欄位大於 25 的記錄:

import numpy as np

# Original structured array
students = np.array([(1, 'Alice', 25), (2, 'Bob', 23), (3, 'Charlie', 30)],
                    dtype=[('ID', 'i4'), ('Name', 'U10'), ('Age', 'i4')])

# Create a boolean mask where Age > 25
mask = students['Age'] > 25

# Apply the mask to filter the array
filtered_students = students[mask]
print(filtered_students)

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

[(3, 'Charlie', 30)]

合併結構化陣列

NumPy 中的結構化數組合並用於沿單個軸(通常是行)合併具有相同 dtype 的陣列。

在 NumPy 中,np.concatenate() 函式用於沿現有軸連線陣列。對於結構化陣列,這要求所有陣列共享相同的 dtype。

示例

在下面的示例中,我們使用 np.concatenate() 函式將兩個具有相同資料型別的結構化數組合併為一個數組:

import numpy as np

# Define two structured arrays with the same dtype
students1 = np.array([(1, 'Alice', 25), (2, 'Bob', 23)],
                     dtype=[('ID', 'i4'), ('Name', 'U10'), ('Age', 'i4')])
students2 = np.array([(3, 'Charlie', 30), (4, 'David', 28)],
                     dtype=[('ID', 'i4'), ('Name', 'U10'), ('Age', 'i4')])

# Concatenate the arrays
combined_students = np.concatenate((students1, students2))
print(combined_students)

產生的結果如下:

[(1, 'Alice', 25) (2, 'Bob', 23) (3, 'Charlie', 30) (4, 'David', 28)]

重塑結構化陣列

NumPy 中的結構化陣列重塑涉及在保留其資料結構的同時更改陣列的形狀。這意味著在重塑前後元素(行)的總數保持不變。

在 NumPy 中,np.reshape() 函式用於更改結構化陣列的形狀。

示例

在下面的示例中,我們使用 np.reshape() 函式將一維結構化陣列重塑為二維陣列:

import numpy as np

# Define a 1-D structured array
students = np.array([(1, 'Alice', 25), (2, 'Bob', 23), (3, 'Charlie', 30)],
                    dtype=[('ID', 'i4'), ('Name', 'U10'), ('Age', 'i4')])

# Reshape the array from 1-D to 2-D
reshaped_students = np.reshape(students, (3, 1))
print(reshaped_students)

這將陣列從單行記錄轉換為列格式,同時保留如下輸出所示的結構化資料:

[[(1, 'Alice', 25)]
 [(2, 'Bob', 23)][(3, 'Charlie', 30)]]

分割結構化陣列

NumPy 中的結構化陣列分割涉及根據某些條件或大小將單個結構化陣列劃分為多個數組。

在 NumPy 中,np.split() 函式用於沿指定的軸將陣列分割成多個子陣列。對於結構化陣列,此函式要求陣列沿元素可以均勻分佈的軸進行分割。

示例

在這個例子中,我們使用 np.split() 函式將結構化陣列分成兩等份:

import numpy as np

# Define a structured array
students = np.array([(1, 'Alice', 25), (2, 'Bob', 23), (3, 'Charlie', 30), (4, 'David', 28)],
                    dtype=[('ID', 'i4'), ('Name', 'U10'), ('Age', 'i4')])

# Split the array into 2 equal parts
split_students = np.split(students, 2)
print(split_students[0])
print(split_students[1])

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

[(1, 'Alice', 25) (2, 'Bob', 23)]
[(3, 'Charlie', 30) (4, 'David', 28)]
廣告