Python Numpy – Add A Constant To All The Elements Of Array

◀CC++C#DartGolangJavaJavaScriptKotlinPHPPythonRRustSwiftTypeScriptUNITS▶
  • Free Android Apps
  • Learn Python - Free Android AppLearn Python
  • NumPy Array Basics
  • NumPy - Create 1D array
  • NumPy - Create 2D array
  • NumPy - Create 3D array
  • NumPy - Create array with random values
  • NumPy - Print array
  • NumPy - Save array to file and load array from file
  • NumPy - Reshape array
  • NumPy - Array with zeros
  • NumPy - Array with ones
  • NumPy – Initialize array with a range of numbers
  • NumPy – Access array elements using index
  • NumPy - Get specific row
  • NumPy – Get array shape
  • NumPy – Get array size
  • NumPy - Iterate over array
  • NumPy - Duplicate or copy array to another array
  • NumPy - Concatenate arrays
  • NumPy - Reverse array
  • NumPy – Stack arrays vertically
  • NumPy – Stack arrays horizontally
  • NumPy – Split array into smaller arrays
  • NumPy - Array Slicing
  • NumPy – Array dot product
  • NumPy – Array cross product
  • NumPy Mathematical Functions
  • NumPy sqrt()
  • NumPy max()
  • NumPy amax()
  • NumPy Statistical Functions
  • NumPy sum()
  • NumPy average()
  • NumPy mean()
  • NumPy median()
  • NumPy std()
  • NumPy var()
  • NumPy Conversions
  • Convert NumPy Array to List
  • Convert List to NumPy Array
  • NumPy Logic Functions
  • NumPy all()

Numpy Array - Add a constant to all elements of the array

Adding a constant to a NumPy array is as easy as adding two numbers.

To add a constant to each and every element of an array, use addition arithmetic operator +. Pass array and constant as operands to the addition operator as shown below.

output = arr + c

where

  • arr is a numpy array.
  • c is a constant.
  • output is the resulting numpy array.

Examples

1. Add a constant of 3 to each element in the array

In the following python example, we will add a constant 3 to an array arr. The resulting array is stored in output and print to the standard output.

Python Program

import numpy as np #2D array arr = (np.arange(8)*2).reshape(2,4) #print array print("The array\n", arr) #adding a constant to all the elemnets of array output = arr + 3 print("\nAfter adding a constant to all the elemnets of array\n", output)

Output

Python Numpy Array - Add a constant

Summary

In this NumPy Tutorial, we learned how to add a constant to each of the element in numpy array using addition operator.

Python Libraries

PythondatetimePythonflaskPythonjsonPythonloggingPythonmathPythonmysqlPythonMatplotlibPythonnltkPythonnumpyPythonopencvPythonpandasPythonphonenumbersPythonpicklePythonpillowPythonpymongoPythonrandomPythonrequestsPythonseleniumPythonsqlite3Pythontkinter

Tag » Add Element In Matrix Python