NumPy, the Python powerhouse for scientific computing, provides an array of tools to efficiently manipulate and analyze data. Among its key functionalities lies numpy.add()
a potent function that performs element-wise addition on NumPy arrays.
numpy.add() Syntax
Syntax : numpy.add(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘add’)
Parameters :
- arr1 : [array_like or scalar] Input array.
- arr2 : [array_like or scalar] Input array. out : [ndarray, optional] A location into which the result is stored. -> If provided, it must have a shape that the inputs broadcast to. -> If not provided or None, a freshly-allocated array is returned.
- where : [array_like, optional] Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone.
- **kwargs :Allows to pass keyword variable length of argument to a function. Used when we want to handle named argument in a function.
Return : [ndarray or scalar] The sum of arr1 and arr2, element-wise. Returns a scalar if both arr1 and arr2 are scalars.
What is numpy.add() in Python?
NumPy’s numpy.add()
is a function that performs element-wise addition on NumPy arrays. This means it adds the corresponding elements between two arrays, element by element, instead of treating them as single values. numpy.add() function is used when we want to compute the addition of two arrays. It adds arguments element-wise. If the shape of two arrays is not the same, that is arr1. shape != arr2.shape, they must be broadcastable to a common shape (which may be the shape of one or the other).
Add Elements in Numpy Arrays
Here are the different example of Add Elements in Numpy Array using numpy.add() with different example below:
- Use numpy.add() on two scalars
- Use Numpy add with one array and one scalar
- Add two same-sized Numpy arrays
- Add differently sized Numpy arrays via broadcasting (i.e., add a vector to a matrix)
Use numpy.add() Function to Add Two Numbers
In this example, we have two scalar values, num1
and num2
. The np.add()
function is used to add these two scalar values, and the result is printed. The function performs element-wise addition, and the output is the sum of the two scalars.
Python
import numpy as geek
in_num1 = 10
in_num2 = 15
print ( "1st Input number : " , in_num1)
print ( "2nd Input number : " , in_num2)
out_num = geek.add(in_num1, in_num2)
print ( "output number after addition : " , out_num)
|
Output
1st Input number : 10
2nd Input number : 15
output number after addition : 25
Use NumPy add
with One Array and One Scalar
Here, we have a NumPy array array1
and a scalar value scalar
. The np.add()
function is applied to add the scalar to each element of the array. This demonstrates the broadcasting capability of NumPy, where the scalar is automatically broadcasted to match the shape of the array.
Python3
import numpy as np
array1 = np.array([ 9 , 7 , 12 ])
scalar = 4
result = np.add(array1, scalar)
print ( "Result of adding array and scalar:" , result)
|
Output
Result of adding array and scalar: [13 11 16]
NOTE: In-place addition: You can also use the += operator to perform in-place addition of two arrays or a scalar and an array. This modifies the first array instead of creating a new one.
Add Two Same-sized NumPy Arrays
The numpy.add() function is a part of the NumPy library in Python, and can be used to add two arrays element-wise. Here’s In this example, we have two NumPy arrays, array1
and array2
, of the same size. The np.add()
function is applied to add the corresponding elements of the two arrays. The result is a new array with the sum of the corresponding elements.
Python3
import numpy as geek
a = geek.array([ 1 , 2 , 3 ])
b = geek.array([ 4 , 5 , 6 ])
c = geek.add(a, b)
print (c)
|
Output
[5 7 9]
Add Differently Sized NumPy Arrays via Broadcasting
Here, we have a 2D NumPy array (matrix
) and a 1D NumPy array (vector
). The np.add()
function is used to add the vector to each row of the matrix, taking advantage of NumPy’s broadcasting feature. The vector is automatically extended to match the size of the matrix, allowing the addition to be performed element-wise.
Python
import numpy as np
matrix = np.array([[ 2 , - 7 , 5 ], [ - 6 , 2 , 0 ]])
vector = np.array([ 3 , 6 , 9 ])
result = np.add(matrix, vector)
print ( "Result of adding a vector to a matrix via broadcasting:" )
print (result)
|
Output
Result of adding a vector to a matrix via broadcasting:
[[ 5 -1 14]
[-3 8 9]]
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow. Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples. The below Python section contains a wide collection of Python programming examples. These Python c
11 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
10 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list(). Let's look at a simple exa
3 min read
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
5 min read