壓縮 NumPy 陣列

Muhammad Maisam Abbas 2023年1月30日

帶有 `list(zip())` 函式的 NumPy Zip

``````import numpy as np

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

c = np.array(list(zip(a, b)))

print(c)
``````

``````[[1 2]
[3 4]
[5 6]
[7 8]]
``````

使用 `numpy.stack()` 函式的 NumPy Zip

``````import numpy as np

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

c = np.stack((a, b), axis=1)

print(c)
``````

``````[[1 2]
[3 4]
[5 6]
[7 8]]
``````

使用 `numpy.column_stack()` 函式的 NumPy Zip

`numpy.column_stack()` 函式是另一種方法，可用於在 Python 中將兩個一維陣列壓縮為單個二維陣列。`numpy.column_stack()` 函式用於將兩個或多個一維陣列作為列連線到單個二維陣列中。我們不必為此方法指定任何軸引數。請參考以下程式碼示例。

``````import numpy as np

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

d = np.column_stack((a, b))

print(d)
``````

``````[[1 2]
[3 4]
[5 6]
[7 8]]
``````

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn