Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Numpy exercise
  • pandas
  • Matplotlib
  • Data visulisation
  • EDA
  • Machin Learning
  • Deep Learning
  • NLP
  • Data science
  • ML Tutorial
  • Computer Vision
  • ML project
Open In App
Next Article:
numpy.add() in Python
Next article icon

numpy.add() in Python

Last Updated : 21 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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
# numpy.add() function # when inputs are scalar  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  # Numpy array and a scalar array1 = np.array([9, 7, 12]) scalar = 4  # Using numpy.add() with an array and a scalar 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  # Define two arrays a = geek.array([1, 2, 3]) b = geek.array([4, 5, 6])  # Add the arrays element-wise c = geek.add(a, b)  # Print the result 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  # NumPy array and a smaller array (vector) matrix = np.array([[2, -7, 5], [-6, 2, 0]]) vector = np.array([3, 6, 9])  # Using numpy.add() to add a vector to a matrix via broadcasting 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]] 

Next Article
numpy.add() in Python

J

jana_sayantan
Improve
Article Tags :
  • Python
  • Python-numpy
  • Python numpy-Mathematical Function
Practice Tags :
  • python

Similar Reads

    numpy.append() in Python
    numpy.append() function is used to add new values at end of existing NumPy array. This is useful when we have to add more elements or rows in existing numpy array. It can also combine two arrays into a bigger one. Syntax: numpy.append(array, values, axis = None)array: Input array. values: The values
    2 min read
    NumPy Array in Python
    NumPy (Numerical Python) is a powerful library for numerical computations in Python. It is commonly referred to multidimensional container that holds the same data type. It is the core data structure of the NumPy library and is optimized for numerical and scientific computation in Python. Table of C
    2 min read
    numpy.defchararray.add() in Python
    numpy.core.defchararray.add(arr1, arr2): Concatenates two strings element-wise. Parameters: arr1 : array-like or string. arr2 : array-like or string. Returns : Concatenates String. Code #1: Python3 1== # Python Program illustrating # numpy.char.add() method import numpy as np arr1 = ['vdteteAAAa', '
    1 min read
    Python | Numpy numpy.ndarray.__add__()
    With the help of Numpy numpy.ndarray.__add__(), we can add a particular value that is provided as a parameter in the ndarray.__add__() method. Value will be added to each and every element in a numpy array. Syntax: ndarray.__add__($self, value, /) Return: self+value Example #1 : In this example we c
    1 min read
    numpy.char.add() function in Python
    The add() method of the char class in the NumPy module is used for element-wise string concatenation for two arrays of str or unicode. numpy.char.add()Syntax : numpy.char.add(x1, x2)Parameters : x1 : first array to be concatenated (concatenated at the beginning)x2 : second array to be concatenated (
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences