Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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 Array Functions
Next article icon

Numpy Array Indexing

Last Updated : 24 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Array Indexing in NumPy is used to access or modify specific elements of an array. It allows to retrieve data from arrays by specifying the positions (indices) of elements. This is the important feature in NumPy that enables efficient data manipulation and analysis for numerical computing tasks.

Accessing 1D Array

In a 1D array, we can access elements using their zero-based index:

Python
import numpy as np  # Create a 1D NumPy array with five elements arr = np.array([10, 20, 30, 40, 50])  # Access and print the first element of the array print(arr[0])  

Output
10 

Table of Content

  • Slicing Arrays
  • Boolean Indexing
  • Ellipsis (...) in Indexing
  • Using np.newaxis
  • Modifying Array Elements

Access 2-D Array

To access elements, you specify the row index first and the column index second.

Python
import numpy as np   # Define a 2D array matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])  # Access the element at row 1, column 2  print(matrix[1, 2])  

Output
6 

Accessing 3D Arrays

A 3D array can be visualized as a stack of 2D arrays. We need three indices:

  • Depth: Specifies the 2D slice.
  • Row: Specifies the row within the slice.
  • Column: Specifies the column within the row.
Python
import numpy as np  cube = np.array([[[1, 2, 3],                   [4, 5, 6],                   [7, 8, 9]],                                    [[10, 11, 12],                   [13, 14, 15],                   [16, 17, 18]]])  # Access the element at depth 1, row 2, column 0 print(cube[1, 2, 0])  

Output
16 

Slicing Arrays

We can extract a subset of elements using the start:stop:step syntax:

Python
import numpy as np  # Create a 1D NumPy array with six elements arr = np.array([0, 1, 2, 3, 4, 5])  # Use slicing to access a subset of the array print(arr[1:4])   

Output
[1 2 3] 

For multidimensional arrays, slicing can be applied to each dimension:

Python
import numpy as np  # Create a 2D NumPy array (matrix) with three rows and three columns matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])  # Use slicing to extract a submatrix print(matrix[0:2, 1:3])  

Output
[[2 3]  [5 6]] 

Boolean Indexing

Boolean indexing allows we to filter elements based on conditions:

Python
import numpy as np  # Create a 1D NumPy array with five elements arr = np.array([10, 15, 20, 25, 30])  # Use boolean indexing to filter elements greater than 20 print(arr[arr > 20])  

Output
[25 30] 

Use logical operators like & (and), | (or), and ~ (not):

Python
import numpy as np   # Create a 1D NumPy array with five elements arr = np.array([10, 15, 20, 25, 30])  # Use boolean indexing with multiple conditions to filter elements print(arr[(arr > 10) & (arr < 30)])   

Output
[15 20 25] 

Ellipsis (...) in Indexing

The ellipsis (...) is a shorthand for selecting all dimensions not explicitly mentioned:

Python
import numpy as np  cube = np.random.rand(4, 4, 4)  # Selects the first "slice" along the last axis print(cube[..., 0])   

Output
[[0.92937637 0.11283562 0.87685485 0.1698762 ]  [0.48812469 0.89827444 0.6408755  0.8818098 ]  [0.97334939 0.51590585 0.2744543  0.4618385 ]  [0.74940947 0.63351317 0.44032189 0.237636  ]] 

Using np.newaxis

The np.newaxis keyword adds a new axis, increasing the array's dimensions:

Python
import numpy as np  # Create a 1D NumPy array with three elements arr = np.array([1, 2, 3])  # Add a new axis to convert the 1D array into a 2D column vector # arr[:, np.newaxis] inserts a new axis along the second dimension  print(arr[:, np.newaxis])   

Output
[[1]  [2]  [3]] 

Modifying Array Elements

NumPy allows direct modification of array elements using indexing:

Python
import numpy as np   # Create a 1D NumPy array with four elements arr = np.array([1, 2, 3, 4])  # Modify elements in the array using slicing arr[1:3] = 99  # Print the updated array to see the changes print(arr)  

Output
[ 1 99 99  4] 

Next Article
NumPy Array Functions
author
kumar_satyam
Improve
Article Tags :
  • Python
  • AI-ML-DS
  • Python-numpy
Practice Tags :
  • python

Similar Reads

  • Numpy - Array Creation
    Numpy Arrays are grid-like structures similar to lists in Python but optimized for numerical operations. The most straightforward way to create a NumPy array is by converting a regular Python list into an array using the np.array() function. Let's understand this with the help of an example: [GFGTAB
    5 min read
  • NumPy Array Functions
    NumPy array functions are a set of built-in operations provided by the NumPy library that allow users to perform various tasks on arrays. With NumPy array functions, you can create, reshape, slice, sort, perform mathematical operations, and much more—all while taking advantage of the library's speed
    3 min read
  • Numpy - Iterating Over Arrays
    NumPy provides flexible and efficient ways to iterate over arrays of any dimensionality. For a one-dimensional array, iterating is straightforward and similar to iterating over a Python list. Let's understand with the help of an example: [GFGTABS] Python import numpy as np # Create a 1D array arr =
    3 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 - ndarray
    ndarray((short for N-dimensional array)) is a core object in NumPy. It is a homogeneous array which means it can hold elements of the same data type. It is a multi-dimensional data structure that enables fast and efficient manipulation of large dataset Let's understand with a simple example: [GFGTAB
    3 min read
  • numpy.asarray() in Python
    numpy.asarray()function is used when we want to convert input to an array. Input can be lists, lists of tuples, tuples, tuples of tuples, tuples of lists and arrays. Syntax : numpy.asarray(arr, dtype=None, order=None) Parameters : arr : [array_like] Input data, in any form that can be converted to a
    2 min read
  • numpy.asfarray() in Python
    numpy.asfarray()function is used when we want to convert input to a float type array. Input includes scalar, lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. Syntax : numpy.asfarray(arr, dtype=type 'numpy.float64') Parameters : arr : [array_like] Input data, in any for
    2 min read
  • Basics of NumPy Arrays
    NumPy stands for Numerical Python. It is a Python library used for working with an array. In Python, we use the list for the array but it's slow to process. NumPy array is a powerful N-dimensional array object and is used in linear algebra, Fourier transform, and random number capabilities. It provi
    5 min read
  • numpy.array_str() in Python
    numpy.array_str()function is used to represent the data of an array as a string. The data in the array is returned as a single string. This function is similar to array_repr, the difference being that array_repr also returns information on the kind of array and its data type. Syntax : numpy.array_st
    2 min read
  • Declaring an Array in Python
    An array is a container used to store the same type of elements such as integer, float, and character type. An Array is one of the most important parts of data structures. In arrays, elements are stored in a contiguous location in a memory. We can access the array elements by indexing from 0 to (siz
    4 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