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:
Replace NumPy array elements that doesn't satisfy the given condition
Next article icon

Replace NumPy array elements that doesn't satisfy the given condition

Last Updated : 25 Oct, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes in Numpy array, we want to apply certain conditions to filter out some values and then either replace or remove them. The conditions can be like if certain values are greater than or less than a particular constant, then replace all those values by some other number.

For this, we can use Relational operators like '>', '<', etc and other functions like numpy.where().

Method 1: Using Relational operators

Example 1: In 1-D Numpy array

Python3
# Importing Numpy module import numpy as np  # Creating a 1-D Numpy array n_arr = np.array([75.42436315, 42.48558583, 60.32924763]) print("Given array:") print(n_arr)  print("\nReplace all elements of array which are greater than 50. to 15.50") n_arr[n_arr > 50.] = 15.50  print("New array :\n") print(n_arr) 

Output:

In the above question, we replace all values greater than 50 with 15.50 in 1-D Numpy array.

Example 2(A): In 2-D Numpy array

Python3
# Importing Numpy module import numpy as np  # Creating a 2-D Numpy array n_arr = np.array([[45.42436315, 52.48558583, 10.32924763],                   [5.7439979, 50.58220701, 25.38213418]]) print("Given array:") print(n_arr)  print("\nReplace all elements of array which are greater than 30. to 5.25") n_arr[n_arr > 30.] = 5.25  print("New array :\n") print(n_arr) 

Output:

In the above question, we replace all values greater than 30 with 5.25 in 2-D Numpy array.

Example 3: In 3-D Numpy array

Python3
# Importing Numpy module import numpy as np  # Creating a 3-D Numpy array n_arr = np.array([[[11, 25.5, 70.6], [30.9, 45.5, 55.9], [20.7, 45.8, 7.1]],                   [[50.1, 65.9, 8.2], [70.4, 85.8, 10.3], [11.3, 22.2, 33.6]],                   [[19.9, 69.7, 36.8], [1.2, 5.1, 24.4], [4.9, 20.8, 96.7]]])  print("Given array:") print(n_arr)  print("\nReplace all elements of array which are less than 10 to Nan") n_arr[n_arr < 10.] = np.nan  print("New array :\n") print(n_arr) 

Output:

In the above question, we replace all values less than 10 with Nan in 3-D Numpy array.

Method 2: Using numpy.where()

It returns the indices of elements in an input array where the given condition is satisfied.

Example 1: 

Python3
# Importing Numpy module import numpy as np  # Creating a 2-D Numpy array n_arr = np.array([[45, 52, 10],                   [1, 5, 25]])  print("Given array:") print(n_arr)  print("\nReplace all elements of array which are \ greater than or equal to 25 to 0")  print("else remains the same ") print(np.where(n_arr >= 25, 0, n_arr)) 

Output:

In the above question, we replace all values greater than or equal to 25 with 0, else remain the same.

Example 2:

Python3
# Importing Numpy module import numpy as np  # Creating a 2-D Numpy array n_arr = np.array([[45, 52, 10],                   [1, 5, 25],                   [50, 40, 81]])  print("Given array:") print(n_arr)  print("\nReplace all elements of array which are \ less than or equal to 25 with Nan")  print("else with 1 ") print(np.where(n_arr <= 25, np.nan, 1)) 

Output: 

In the above question, we replace all values less than or equal to 25 with Nan, else with 1.


Next Article
Replace NumPy array elements that doesn't satisfy the given condition

V

vanshgaur14866
Improve
Article Tags :
  • Python
  • Python-numpy
  • Python numpy-Indexing
Practice Tags :
  • python

Similar Reads

    NumPy - Arithmetic operations with array containing string elements
    Numpy is a library of Python for array processing written in C and Python. Computations in numpy are much faster than that of traditional data structures in Python like lists, tuples, dictionaries etc. due to vectorized universal functions. Sometimes while dealing with data, we need to perform arith
    2 min read
    How to Remove rows in Numpy array that contains non-numeric values?
    Many times NumPy arrays may contain NaN values that need to be removed to ensure the array is free from unnecessary or invalid data. This can be achieved using the np.isnan() function along with the Bitwise NOT operator. Note that this approach specifically targets NaN values and may not handle othe
    2 min read
    Python | Replace negative value with zero in numpy array
    Given numpy array, the task is to replace negative value with zero in numpy array. Let’s see a few examples of this problem. Method #1: Naive Method Python3 # Python code to demonstrate # to replace negative value with 0 import numpy as np ini_array1 = np.array([1, 2, -3, 4, -5, -6]) # printing init
    4 min read
    How to check whether the elements of a given NumPy array is non-zero?
    In NumPy with the help of any() function, we can check whether any of the elements of a given array in NumPy is non-zero. We will pass an array in the any() function if it returns true then any of the element of the array is non zero if it returns false then all the elements of the array are zero. S
    1 min read
    How to Remove columns in Numpy array that contains non-numeric values?
    Many times we have non-numeric values in NumPy array. These values need to be removed, so that array will be free from all these unnecessary values and look more decent. It is possible to remove all columns containing Nan values using the Bitwise NOT operator and np.isnan() function. Example 1: Pyth
    2 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