查詢NumPy陣列元素的和與積


NumPy是一個用於科學計算和處理大型數值資料的Python包。它支援多維陣列和矩陣,以及用於操作它們的大量數學函式。在本教程中,我們將重點介紹兩個最常用的NumPy函式:sum()prod()。這兩個函式分別用於計算NumPy陣列中所有元素的和與積。

安裝

使用pip在終端中安裝numpy包

pip install numpy

成功安裝後,按如下所示匯入它:

import numpy as np

語法

NumPy提供了兩個用於計算陣列和與積的有用函式:

  • np.sum() - np.sum(array, axis=None, dtype=None, out=None, keepdims=<no value>)

  • np.prod() - np.prod(array, axis=None, dtype=None, out=None, keepdims=<no value>)

您想要用於運算的NumPy陣列是您提供給這兩個函式的第一個引數。如果未指定可選引數axis,則函式將計算陣列的和或積。可以使用axis引數指定將執行計算的軸。可以使用可選引數dtype指定返回值的資料型別。如果指定了可選引數out,則函式將把輸出放在指定的陣列中。最後,您可以使用可選引數keepdims決定是否將輸出陣列的維度與輸入陣列的維度保持一致。

演算法

  • 匯入NumPy庫。

  • 建立一個NumPy陣列。

  • 使用sum()或prod()函式計算陣列中元素的和或積。

示例

import numpy as np

# Example 1: Calculate the sum of all the elements in a 1D array
a = np.array([1, 2, 3, 4, 5])
total_sum = np.sum(a)
print(total_sum) # Output: 15

# Example 2: Calculate the product of all the elements in a 1D array
b = np.array([2, 3, 4, 5])
total_prod = np.prod(b)
print(total_prod) # Output: 120

# Example 3: Calculate the sum of all the elements in a 2D array along the columns
c = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
col_sum = np.sum(c, axis=0)
print(col_sum) # Output: [12 15 18]

輸出

15
120
[12 15 18]

示例

如何在NumPy中使用sum()和prod()函式計算二維陣列中所有元素的和與積。

import numpy as np

# Create a 2D NumPy array
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Add together all the array's components to get the total.
total_sum = np.sum(a)
print(total_sum) # Output: 45

# compute the array's total elements' product.
total_prod = np.prod(a)
print(total_prod) # Output: 362880

# Calculate the sum of all the elements in the array using a for loop
sum = 0
for i in range(len(a)):
   sum += a[i]
print(sum) # Output: 45

輸出

45
362880
[12 15 18]

可以使用for迴圈或列表推導式中的for表示式遍歷陣列的元素,並將每個元素新增到變數total中。迭代所有元素後,將顯示陣列中所有元素的總和。

廣播

此外,NumPy陣列支援廣播,這是一種強大的技術,允許NumPy對不同形狀的陣列進行運算。較小的陣列和較大的陣列透過彼此廣播來具有相同的形狀。這是一個使用廣播計算NumPy陣列的和與積的示例:

示例

import numpy as np

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

# Calculate the sum of the two arrays
total_sum = a + b
print(total_sum) # Output: [5 7 9]

# Calculate the product of the two arrays
total_prod = a * b
print(total_prod) # Output: [ 4 10 18]

輸出

[5 7 9]
[ 4 10 18]

在這個例子中,我們對兩個不同形狀的陣列執行算術運算。但是,廣播功能會自動將較小的陣列廣播到較大的陣列上,以便形狀與運算相容。

應用

計算NumPy陣列的和與積的能力在許多科學和工程應用中都很有用。一些應用示例包括:

  • 根據儲存在NumPy陣列中的銷售資料計算總收入

  • 使用儲存在NumPy陣列中的溫度資料計算城市一段時間內的平均溫度

  • 查詢儲存在NumPy陣列中的一組資料的最大值和最小值

  • 計算儲存為NumPy陣列的兩個向量之間的點積

結論

在這篇文章中,我們學習瞭如何使用sum()prod()方法計算NumPy陣列元素的和與積,以及如何使用廣播對不同形狀的陣列執行算術運算。NumPy之所以被科學和技術界選中,是因為它能夠進行高效的陣列計算。

更新於:2023年8月21日

瀏覽量:395

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.