Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

NumPy 求和


求和

求和与加法有什么区别?

加法是在两个参数之间进行的,而求和则是在 n 个元素上进行的。

示例

将 arr1 中的值添加到 arr2 中的值

import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([1, 2, 3])

newarr = np.add(arr1, arr2)

print(newarr)
亲自尝试 »

返回值: [2 4 6]

示例

对 arr1 和 arr2 中的值进行求和

import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([1, 2, 3])

newarr = np.sum([arr1, arr2])

print(newarr)
亲自尝试 »

返回值: 12


沿轴求和

如果指定 axis=1,NumPy 将对每个数组中的数字求和。

示例

在以下数组中沿第 1 个轴进行求和

import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([1, 2, 3])

newarr = np.sum([arr1, arr2], axis=1)

print(newarr)
亲自尝试 »

返回值: [6 6]


累积和

累积和表示对数组中的元素进行部分求和。

例如,[1, 2, 3, 4] 的部分和将是 [1, 1+2, 1+2+3, 1+2+3+4] = [1, 3, 6, 10]。

使用 cumsum() 函数执行部分求和。

示例

在以下数组中执行累积求和

import numpy as np

arr = np.array([1, 2, 3])

newarr = np.cumsum(arr)

print(newarr)
亲自尝试 »

返回值: [1 3 6]



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.