Python NumPy Replace + Examples

In this Python NumPy tutorial, we will learn how to replace values in NumPy array Python. With the Python NumPy replace function, we will cover these topics.

  • Python numpy replace nan with 0
  • Python numpy replace values in array
  • Python numpy replace 0 with 1
  • Python numpy replace all values in array
  • Python numpy replace inf with 0
  • Python numpy replace row
  • Python numpy replace column
  • Python numpy replace negative values with zeros
  • Python numpy replace string in array
  • Python np.where replace
  • Python numpy remove last element
  • Python numpy random choice replace
  • Python numpy remove duplicates
  • Python numpy remove column from array
  • Python numpy remove element by index

Python numpy replace

  • In this section, we will discuss how to replace the values in the Python NumPy array.
  • To perform this particular task we are going to use numpy.clip() function and this method return a NumPy array where the values less than the specified limit are replaced with a lower limit.
  • In Python the numpy.clip() function assigns the interval and the elements which are outside the interval are clipped to the interval edges.
  • This method is basically the combination of Python numpy.minimum() and numpy.maximum() function.

Syntax:

Let’s have a look at the Syntax and understand the working of numpy.clip() function

numpy.clip
          (
           a,
           a_min,
           a_max,
           out=None,
          )
  • It consists of a few parameters
    • a: This parameter indicates the input array containing elements to clip.
    • a_min: This parameter specifies the lower value of the defined interval. It will check the condition if a_min value is none then clipping is not performed on the lower edge.
    • a_max: This parameter indicates the maximum value of the defined interval.
    • out: By default, it takes none value and signifies the array in which the result will be stored and out must be of the right shape.

Example:

Let’s take an example and check how to replace the values in NumPy array Python

Source Code:

import numpy as np

new_array = np.array([12,15,17,18,23,26,45])

out = np.clip(new_array, 12, 16)
print("The clipped array:", out)

In the above code, we have imported the numpy module and then used the numpy.array() function for creating an array.

After that, we used the numpy.clip() function to limit the lower interval and higher interval. In this example, we have used three arguments a_min=12, a_max=16.

So now the lower limit will be 12 and the higher limit will be ’16’. In this program, all the values whose value is less than ’16’ will remain the same and if the value is greater than 16 then it will be flipped with 16.

Here is the Screenshot of the following given code

Python numpy replace
Python numpy replace

Read Check if NumPy Array is Empty in Python

Python numpy replace nan with 0

  • In this Program, we will learn how to replace nan value with 0 in Python.
  • In Python to replace nan values with zero, we can easily use the numpy.nan_to_num() function. This function will help the user for replacing the nan values with 0 and infinity with large finite numbers.

Syntax:

Here is the Syntax of the Python numpy.nan_to_num() function

numpy.nan_to_num
                (
                 x,
                 copy=True,
                 nan=0.0,
                 posinf=None,
                 neginf=None
                )
  • It consists of a few parameters
    • x: This parameter indicates the input array.
    • copy: By default it takes ‘True’ value and this occurs when casting to an array is not required a copy.
    • nan: This parameter will check the condition if there is no value passed then the nan values will be replaced with 0. By default it takes 0 value as an argument in function.
    • posinf: This parameter specifies fill positive infinity values.

Example:

Let’s take an example and understand the working of numpy.nan_to_num() function

Source Code:

import numpy as np

new_arr = np.array([[13, np.nan, 16,np.nan], [17, np.NaN, 14,np.nan]])
print("Creation of array:",new_arr)
new_output = np.nan_to_num(new_arr)
print("Replace nan with zero:",new_output)

In the above code, we have used the np.array() function for creating an array that contains integer and numerical values. Now we want to replace the nan values with zero by using the numpy.nan_to_num. In this function, we have passed the array as an argument.

Here is the execution of the following given code

Python numpy replace nan with 0
Python numpy replace nan with 0

As you can see in the screenshot the output displays the newly updated array.

Read Python NumPy zeros

Python numpy replace values in array

  • Here we will discuss how to replafacece values in Python numpy array.
  • By using the np.where() function, we can easily perform this task. In Python np.where() function is used to choose the elements from the numpy array depending on condition.
  • In this example, we will create an array that contains integer values and by using np.where() function we will give the condition if the value ’19’ is less than the array containing values then it will replace by ’69’.

Syntax:

Here is the Syntax of numpy.where() function

numpy.where
           (
            condition
            [,
            x,
            y
            ]
           )

Example:

import numpy as np
 
new_arr_ele = np.array([15, 25, 44, 56, 74, 2, 19])
result = np.where(new_arr_ele < 19, 69, new_arr_ele)
print("Replace value:",result)

Here is the implementation of the following given code

Python Numpy replace values in array
Python Numpy replace values in an array

If you want to get detailed information regarding numpy.where() function. You can refer to our article Python numpy where.

Python numpy replace 0 with 1

  • In this section, we will discuss how to replace 0 value with 1 in NumPy Python.
  • To do this task we are going to use the numpy.place(). In Python, the numpy.place() is used to change in the numpy array as per the conditions and values must be used first N values put into a NumPy array.
  • This method is available in the numpy package module and can be imported by the numpy library as np and always return the updated array which was given as input array.

Syntax:

Here is the Syntax of NumPy.place() method

NumPy.place
           (
            arr,
            mask,
            vals
           )

Example:

import numpy as np
 
new_array = np.array([0,1,2,3,4,5,6,7,8])
np.place(new_array, new_array<1, [1])
print("Replace 0 with 1:",new_array)

In the above code, we imported the numpy library and then initialize an array by using the np.array() function. After that, we have used the np.place() function and assigned the array condition that if the value is less than 1 then it will replace 1.

As per the condition, the value is 0 which is less than 1 and it will be replaced with 1

Here is the Screenshot of the following given code

Python numpy replace 0 with 1
Python numpy replace 0 with 1

Read Python NumPy Sum

Python numpy replace all values in array

  • In this section, we will discuss how to replace all values in Python NumPy array.
  • To solve this problem we are going to use the numpy.clip() function and this method return a NumPy array where the values less than the specified limit are replaced with a lower limit.
  • In this example, we have imported the numpy library and then created an array by using the np.array() function. After that we have declared a variable ‘new_result’ and assign the np.clip() function. It will check the condition if the value is greater than 16 then it will replace with a 16 value.

Source Code:

import numpy as np

new_val_element = np.array([8,4,17,18,45,78,98])
new_result= np.clip(new_val_element, 17, 16)
print("Replace all values:", new_result)

You can refer to the below Screenshot

Python numpy replace all values in array
Python numpy replace all values in the array

Check out Python NumPy Random

Python numpy replace inf with 0

  • In this Program, we will discuss how to replace numpy.inf values with 0 in Python by using the numpy.where() function.
  • In Python, the inf stands for positive infinity in numpy and it is an infinite number and mostly used for the computation of algorithms. It will check the condition if the input value is numpy.inf then it will return a positive infinity.
  • In this example, we have to replace the inf values with 0. To do this task we are going to use the np,where() function and it will set the condition that arr===np.inf then replace with 0.

Example:

import numpy as np
from numpy import inf

new_array = np.array([np.inf,15,np.inf,17,np.inf])
result= np.where(new_array==np.inf, 0, new_array) 
print(result)

Here is the implementation of the following given code

Python numpy replace inf with 0
Python numpy replace inf with 0

Read Python NumPy max

Python numpy replace row

  • In this section, we will discuss how to replace row in Python numpy array.
  • To replace a row in an array we will use the slicing and * operator method. It will help the user for replacing rows elements. Firstly we will import the numpy library and then create a numpy array by using the np.array() function.
  • Now we will use the array condition and create a slicing for selecting the row then we will multiply the selected row with 4. It will update all the elements of 3 rows.

Example:

import numpy as np

new_array = np.array([[15, 17, 35],
                   [18, 22, 34],
                   [78, 84, 34]])
new_array[2:,] = new_array[2:,] * 4
print(new_array)

Here is the Screenshot of the following given code

Python numpy replace row
Python numpy replace row

Read Python NumPy shape with examples

Python numpy replace column

  • In this section, we will discuss how to replace a column in Python numpy array.
  • To do this task we are going to use the slicing method. Firstly we will import the numpy library and then initialize an array by using the np.ones() function. Once you will execute this function it will display the array that contains only one’s value.
  • Now we want to replace one column from the array and replace one’s value with zeros, To do this task we are going to apply the slicing method.

Example:

import numpy as np

new_arr = np.ones((3,3))
print("Creation of array:",new_arr)
new_arr[:, 1] =  0
print("Replace column from array:",new_arr)

Here is the execution of the following given code

Python numpy replace column
Python numpy replace column

Read Python reverse NumPy array

Python numpy replace negative values with zeros

  • In this program, we will discuss how to replace negative values with zeros in NumPy Python.
  • To perform this particular task we are going to use the np.place() function and it is used to change in numpy array as per the conditions and values must be used first N values put into a NumPy array.

Syntax:

Here is the Syntax of Python numpy.place() function

NumPy.place
           (
            arr,
            mask,
            vals
           )

Source Code:

import numpy as np
 
new_values = np.array([0,1,2,-7,4,-5,6,-7,8])
np.place(new_values, new_values<0, [0])
print("Replace negative values with 0:",new_values)

You can refer to the below Screenshot

Python numpy replace negative values with zeros
Python numpy replace negative values with zeros

Read Python NumPy empty array with examples

Python numpy replace string in array

  • Let us see how to replace a string in Python numpy array by using numpy.char.replace() method.
  • In Python, this function is used to return a copy of the numpy array of string and this method is available in the NumPy package module. In Python this method will check the condition if the argument count is given, then only the first count occurrences is replaced.

Syntax:

Let’s have a look at the Syntax and understand the working of numpy.char.replace() method

char.replace
            (
             a,
             old,
             new,
             count=None
            )
  • It consists of a few parameters
    • a: This parameter indicates the input array string.
    • old: str or inicode
    • count: By default it takes none value and it is an optional parameter if count is given then the first count occurence are replaced.

Example:

Let’s take an example and check how to replace a string in NumPy Python

Source Code:

import numpy as np 

new_str= "John is a Python developer"
result= np.char.replace (new_str, 'is', 'was')
print("Replacing string character:",result)

In the above program, we imported the numpy library and then create a string named ‘new_str’. After that, we have declared a variable ‘result’ and assigned the np.char.replace() function and within this function, we have passed the array and replacing element as an argument. Once you will print ‘result’ then the output will display the newly updated string.

Here is the implementation of the following given code

Python numpy replace string in array
Python numpy replace a string in an array

Read Python NumPy nan

Python np.where replace

  • In this section, we will discuss how to replace the value in NumPy Python by using the np.where() function.
  • In Python, this function is used to return the indices of items which is given in an input array depending on the condition. In this example, we will create an array that contains integer values and by using the np.where() function we will give the condition if the value ’47’ is less than the array containing values then it will replace with ‘105’.

Example:

Let’s take an example and check how to replace the values in an array by using the np.where() function.

Source Code:

import numpy as np
 
new_elements = np.array([45, 78, 126, 78, 47, 86, 189])
print("Creation of array:",new_elements)
new_output = np.where(new_elements < 47, 105, new_elements)
print("Replacing values from array:",new_output)

You can refer to the below Screenshot

Python np where replace
Python np where replace

Read Valueerror: Setting an array element with a sequence

Python numpy remove last element

  • In this Program, we will discuss how to remove the last element in the Python NumPy array.
  • To remove the last element from an array we can easily use the numpy.delete() function. In Python this function is used to remove the elements from a numpy array along with the given axis and this method will always return the newly updated array after applying the numpy.delete() function. It just removes the item which we want to delete.
  • To get detail information on numpy.delete() function you can refer our article Python numpy delete

Example:

import numpy as np
 
new_values = np.array([16, 25, 67, 89, 167, 94, 79])
print("Creation of array:",new_values)
new_result= np.delete(new_values,6)
print("Removing last element from array:",new_result)

Here is the Output of the following given code

Python numpy remove last element
Python numpy remove the last element

Read Python NumPy Average with Examples

Python numpy random choice replace

  • In this section, we will discuss how to replace the elements in the Python NumPy array by using numpy random.choice() function.
  • To perform this particular task we are going to use the numpy random.choice() function. In Python, this function is used to generate a random sample of an array and always return the generated random samples.

Syntax:

Let’s have a look at the Syntax and understand the working of random.choice() function

random.choice
             (
              a,
              size=None,
              replace=True,
              p=None,
             )
  • It consists of a few parameters
    • a: This parameter indicates the input array you want to operate on.
    • size: By default it takes none value and it indicates the size of the array.
    • replace: This parameter checks the condition whether the sample is without replacement or not.
    • p: The probabilites associated with the items of an array.

Example:

import numpy as np
 
new_values = np.array([16, 25, 67, 89, 167, 94, 79,67])
z= np.random.choice(new_values,size=8,replace=False)
print("Random sample generate",z)

Here is the Screenshot of the following given code

Python numpy random choice replace
Python numpy random choice replace

Read Python NumPy absolute value with examples

Python numpy remove duplicates

  • Let us see how to remove duplicates in Python numpy array.
  • To do this task we are going to use the numpy.unique() function for removing the duplicate elements from the NumPy array.
  • In Python numpy.the unique() function is used to find the unique values of a numpy array and always returns a tuple of unique values and a numpy array of associated indices.
  • To get detail information on numpy.delete() function you can refer our article Python numpy unique

Example:

import numpy as np  

new_elements=np.array([156,23,18,156,28,93,156,292])  
new_output=np.unique(new_elements)
print("Remove duplicates from array:",new_output)

Here is the implementation of the following given code

Python numpy remove duplicates
Python numpy remove duplicates

As you can see in the Screenshot the output displays that the duplicate elements that have been removed from the array.

Read Python NumPy square with examples

Python numpy remove column from array

  • In this Program, we will discuss how to remove a column from numpy array in Python.
  • By using the numpy.delete() function we can perform this particular task and within this function, we will specify the axis that will help the user to remove easily column elements from an array.
  • In this example, we have specified the axis value=2 that represents the 2 column elements that will remove from the array.

Source Code:

import numpy as np  

new_array = np.array([[ 14,  26,  89,  43],
               [ 17,  78,  92,  34],
               [ 55,  23, 41, 77],
               ])
result = np.delete(new_array, 2,1) 
print(result)

You can refer to the below Screenshot

Python numpy remove column from array
Python numpy remove column from array

Python numpy remove element by index

We had already covered this topic on Python numpy indexing article. You get all the information regarding numpy indexing

Related Python NumPy tutorials:

In this Python tutorial, we learned how to replace values in NumPy array Python. With the Python NumPy replace function, we will cover these topics.

  • Python numpy replace nan with 0
  • Python numpy replace values in array
  • Python numpy replace 0 with 1
  • Python numpy replace all values in array
  • Python numpy replace inf with 0
  • Python numpy replace row
  • Python numpy replace column
  • Python numpy replace negative values with zeros
  • Python numpy replace string in array
  • Python np.where replace
  • Python numpy remove last element
  • Python numpy random choice replace
  • Python numpy remove duplicates
  • Python numpy remove column from array
  • Python numpy remove element by index