The Wayback Machine - https://web.archive.org/web/20241009174211/https://www.geeksforgeeks.org/indexing-and-selecting-data-with-pandas/
Open In App

Indexing and Selecting Data with Pandas

Last Updated : 31 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Indexing in Pandas : Indexing in pandas means simply selecting particular rows and columns of data from a DataFrame. Indexing could mean selecting all the rows and some of the columns, some of the rows and all of the columns, or some of each of the rows and columns. Indexing can also be known as Subset Selection.

Let’s see some example of indexing in Pandas. In this article, we are using “nba.csv” file to download the CSV, click here.

Selecting some rows and some columns

Let’s take a DataFrame with some fake data, now we perform indexing on this DataFrame. In this, we are selecting some rows and some columns from a DataFrame. Dataframe with dataset.

Suppose we want to select columns Age, College and Salary for only rows with a labels Amir Johnson and Terry Rozier

Our final DataFrame would look like this:

Selecting some rows and all columns

Let’s say we want to select row Amir Jhonson, Terry Rozier and John Holland with all columns in a dataframe.

Our final DataFrame would look like this:

Selecting some columns and all rows

Let’s say we want to select columns Age, Height and Salary with all rows in a dataframe.

Our final DataFrame would look like this:

Pandas Indexing using [ ], .loc[], .iloc[ ], .ix[ ]

There are a lot of ways to pull the elements, rows, and columns from a DataFrame. There are some indexing method in Pandas which help in getting an element from a DataFrame. These indexing methods appear very similar but behave very differently. Pandas support four types of Multi-axes indexing they are:

  • Dataframe.[ ] ; This function also known as indexing operator
  • Dataframe.loc[ ] : This function is used for labels.
  • Dataframe.iloc[ ] : This function is used for positions or integer based
  • Dataframe.ix[] : This function is used for both label and integer based

Collectively, they are called the indexers. These are by far the most common ways to index data. These are four function which help in getting the elements, rows, and columns from a DataFrame.  

Indexing a Dataframe using indexing operator []:

Indexing operator is used to refer to the square brackets following an object. The .loc and .iloc indexers also use the indexing operator to make selections. In this indexing operator to refer to df[].

Selecting a single columns

In order to select a single column, we simply put the name of the column in-between the brackets

Python
# importing pandas package
import pandas as pd

# making data frame from csv file
data = pd.read_csv("nba.csv", index_col ="Name")

# retrieving columns by indexing operator
first = data["Age"]



print(first)

Output:

Selecting multiple columns

In order to select multiple columns, we have to pass a list of columns in an indexing operator.

Python
# importing pandas package
import pandas as pd

# making data frame from csv file
data = pd.read_csv("nba.csv", index_col ="Name")

# retrieving multiple columns by indexing operator
first = data[["Age", "College", "Salary"]]



print(first)

Output:

Indexing a DataFrame using .loc[ ]

This function selects data by the label of the rows and columns. The df.loc indexer selects data in a different way than just the indexing operator. It can select subsets of rows or columns. It can also simultaneously select subsets of rows and columns.

Selecting a single row

In order to select a single row using .loc[] , we put a single row label in a .loc function.

Python
# importing pandas package
import pandas as pd

# making data frame from csv file
data = pd.read_csv("nba.csv", index_col ="Name")

# retrieving row by loc method
first = data.loc["Avery Bradley"]
second = data.loc["R.J. Hunter"]


print(first, "\n\n\n", second)

Output:

As shown in the output image, two series were returned since there was only one parameter both of the times.

Selecting multiple rows

In order to select multiple rows, we put all the row labels in a list and pass that to .loc function.

Python
import pandas as pd

# making data frame from csv file
data = pd.read_csv("nba.csv", index_col ="Name")

# retrieving multiple rows by loc method
first = data.loc[["Avery Bradley", "R.J. Hunter"]]



print(first)

Output:

Selecting two rows and three columns

In order to select two rows and three columns, we select a two rows which we want to select and three columns and put it in a separate list like this:

Dataframe.loc[["row1", "row2"], ["column1", "column2", "column3"]]
Python
import pandas as pd

# making data frame from csv file
data = pd.read_csv("nba.csv", index_col ="Name")

# retrieving two rows and three columns by loc method
first = data.loc[["Avery Bradley", "R.J. Hunter"],
                   ["Team", "Number", "Position"]]



print(first)

Output:

Selecting all of the rows and some columns

In order to select all of the rows and some columns, we use single colon [:] to select all of rows and list of some columns which we want to select like this:

Dataframe.loc[:, ["column1", "column2", "column3"]]
Python
import pandas as pd

# making data frame from csv file
data = pd.read_csv("nba.csv", index_col ="Name")

# retrieving all rows and some columns by loc method
first = data.loc[:, ["Team", "Number", "Position"]]



print(first)

Output:

Indexing a DataFrame using .iloc[ ] :

This function allows us to retrieve rows and columns by position. In order to do that, we’ll need to specify the positions of the rows that we want, and the positions of the columns that we want as well. The df.iloc indexer is very similar to df.loc but only uses integer locations to make its selections.

Selecting a single row

In order to select a single row using .iloc[], we can pass a single integer to .iloc[] function.

Python
import pandas as pd

# making data frame from csv file
data = pd.read_csv("nba.csv", index_col ="Name")


# retrieving rows by iloc method 
row2 = data.iloc[3] 



print(row2)

Output:

Selecting multiple rows

In order to select multiple rows, we can pass a list of integer to .iloc[] function.

Python
import pandas as pd

# making data frame from csv file
data = pd.read_csv("nba.csv", index_col ="Name")

# retrieving multiple rows by iloc method 
row2 = data.iloc [[3, 5, 7]]

print(row2)

Output:

Selecting two rows and two columns

In order to select two rows and two columns, we create a list of 2 integer for rows and list of 2 integer for columns then pass to a .iloc[] function.

Python
import pandas as pd

# making data frame from csv file
data = pd.read_csv("nba.csv", index_col ="Name")


# retrieving two rows and two columns by iloc method 
row2 = data.iloc [[3, 4], [1, 2]]



print(row2)

Output:

Selecting all the rows and a some columns

In order to select all rows and some columns, we use single colon [:] to select all of rows and for columns we make a list of integer then pass to a .iloc[] function.

Python
import pandas as pd

# making data frame from csv file
data = pd.read_csv("nba.csv", index_col ="Name")


# retrieving all rows and some columns by iloc method 
row2 = data.iloc [:, [1, 2]]



print(row2)

Output:

Indexing a using Dataframe.ix[ ] :

Early in the development of pandas, there existed another indexer, ix. This indexer was capable of selecting both by label and by integer location. While it was versatile, it caused lots of confusion because it’s not explicit. Sometimes integers can also be labels for rows or columns. Thus there were instances where it was ambiguous. Generally, ix is label based and acts just as the .loc indexer. However, .ix also supports integer type selections (as in .iloc) where passed an integer. This only works where the index of the DataFrame is not integer based .ix will accept any of the inputs of .loc and .iloc.

Note: The .ix indexer has been deprecated in recent versions of Pandas.

Selecting a single row using .ix[] as .loc[]

In order to select a single row, we put a single row label in a .ix function. This function act similar as .loc[] if we pass a row label as a argument of a function.

Python
# importing pandas package
import pandas as pd
 
# making data frame from csv file
data = pd.read_csv("nba.csv", index_col ="Name")
 
# retrieving row by ix method
first = data.ix["Avery Bradley"]

print(first)
 

Output:

Methods for indexing in DataFrame

FunctionDescription
Dataframe.head() Return top n rows of a data frame.
Dataframe.tail()Return bottom n rows of a data frame.
Dataframe.at[]Access a single value for a row/column label pair.
Dataframe.iat[]Access a single value for a row/column pair by integer position.
Dataframe.tail()Purely integer-location based indexing for selection by position.
DataFrame.lookup()Label-based “fancy indexing” function for DataFrame.
DataFrame.pop()Return item and drop from frame.
DataFrame.xs()Returns a cross-section (row(s) or column(s)) from the DataFrame.
DataFrame.get()Get item from object for given key (DataFrame column, Panel slice, etc.).
DataFrame.isin()Return boolean DataFrame showing whether each element in the DataFrame is contained in values.
DataFrame.where()Return an object of same shape as self and whose corresponding entries are from self where cond is True and otherwise are from other.
DataFrame.mask()Return an object of same shape as self and whose corresponding entries are from self where cond is False and otherwise are from other.
DataFrame.query()Query the columns of a frame with a boolean expression.
DataFrame.insert()Insert column into DataFrame at specified location.

Indexing and Selecting Data with Pandas – FAQs

What is indexing and selecting data with Pandas in Python?

Indexing and selecting data with pandas involve specifying which data points (rows and columns) in a DataFrame or Series you want to access or modify. Pandas provides powerful tools for selecting data based on label indexing, integer indexing, or condition-based filtering.

How to select data based on index in Pandas?

You can select data based on the index using the loc and iloc attributes:

  • loc: Used for label-based indexing. You can specify row labels and the names of columns you want to select.
  • iloc: Used for integer position-based indexing. You specify row and column numbers, which are zero-based integers.
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6],
    'C': [7, 8, 9]
}, index=['one', 'two', 'three'])

# Select data using label-based index
print(df.loc['two'])

# Select data using integer-based index
print(df.iloc[1])

What are the methods of indexing in pandas?

Pandas supports several methods of indexing:

  • Label-based indexing (loc): Selects data based on data index value labels.
  • Integer-based indexing (iloc): Selects data based on the integer position of rows and columns.
  • Boolean indexing: Uses a boolean vector to filter data.
  • Conditional indexing: Uses conditions to filter rows or columns.
  • MultiIndex (hierarchical): Advanced indexing on multiple levels of index rows or columns.

What are types of indexing?

In the broader context beyond pandas, types of indexing include:

  • Single-level indexing: Regular index with a single label for each entry.
  • Multi-level indexing (Hierarchical): Multiple index levels, allowing for more complex data arrangements.
  • Datetime indexing: Specific to time series data, allowing date and time-based indexing.
  • Interval indexing: For data indexed by ranges of values.
  • Categorical indexing: For data categorized based on specific criteria.

What is indexing method?

The indexing method refers to the technique used to organize and access data within a data structure (like a DataFrame or a Series in pandas). These methods are crucial for optimizing data retrieval, updates, and management. They define how data is internally stored and how efficiently you can retrieve or manipulate it.



Previous Article
Next Article

Similar Reads

Selecting rows in pandas DataFrame based on conditions
Let’s see how to Select rows based on some conditions in Pandas DataFrame. Selecting rows based on particular column value using '>', '=', '=', '<=', '!=' operator. Code #1 : Selecting all the rows from the given dataframe in which 'Percentage' is greater than 80 using basic method. [GFGTABS] Python # importing pandas import pandas as pd reco
6 min read
Tensor Indexing in Tensorflow
In the realm of machine learning and deep learning, tensors are fundamental data structures used to represent numerical data with multiple dimensions. TensorFlow, a powerful numerical computation library, equips you with an intuitive and versatile set of operations for manipulating and accessing data within these tensors. Understanding tensor index
10 min read
Numpy Array Indexing
NumPy or Numeric Python is a package for computation on homogenous n-dimensional arrays. In numpy dimensions are called as axes. Why do we need NumPy ? A question arises that why do we need NumPy when python lists are already there. The answer to it is we cannot perform operations on all the elements of two list directly. For example, we cannot mul
8 min read
Querying and selecting specific column in SQLAlchemy
In this article, we will see how to query and select specific columns using SQLAlchemy in and For our examples, we have already created a Students table which we will be using: Selecting specific column in SQLAlchemy:Syntax: sqlalchemy.select(*entities) Where: Entities to SELECT from. This is typically a series of ColumnElement for Core usage and O
4 min read
Dimensionality Reduction with PCA: Selecting the Largest Eigenvalues and Eigenvectors
In data analysis, particularly in multivariate statistics and machine learning, the concepts of eigenvalues and eigenvectors of the covariance matrix play a crucial role. These mathematical constructs are fundamental in techniques such as Principal Component Analysis (PCA), which is widely used for dimensionality reduction and feature extraction. T
7 min read
Selecting Top Features with tsfresh: A Technical Guide
tsfresh (Time Series Feature extraction based on scalable hypothesis tests) is a powerful Python library designed for automatic extraction of numerous features from time series data. It excels at tasks such as classification, regression, and clustering. However, the abundance of features it generates can lead to overfitting, making feature selectio
5 min read
Add a Pandas series to another Pandas series
Let us see how to add a Pandas series to another series in Python. This can be done using 2 ways: append()concat() Method 1: Using the append() function: It appends one series object at the end of another series object and returns an appended series. The attribute, ignore_index=True is used when we do not use index values on appending, i.e., the re
2 min read
Pandas and NumPy Exercise for Data Analysis
NumPy Exercises for Data AnalysisNumPy Array ExercisesHow to create an empty and a full NumPy array?Create a Numpy array filled with all zerosCreate a Numpy array filled with all onesCheck whether a Numpy array contains a specified rowHow to Remove rows in Numpy array that contains non-numeric values?Combining a one and a two-dimensional NumPy Arra
5 min read
Difference between Data Scientist, Data Engineer, Data Analyst
In the world of big data and analytics, there are three key roles that are essential to any data-driven organization: data scientist, data engineer, and data analyst. While the job titles may sound similar, there are significant differences between the roles. In this article, we will explore the differences between data scientist, data engineer, an
5 min read
Data Exploration using Pandas GUI
Data Preprocessing is an important part of the Data Science pipeline, you need to find out about various irregularities in the data, you manipulate your features, etc. Pandas is a tool that we use very often for manipulating the data, along with seaborn and matplotlib for Data Visualization. PandasGUI is a library that makes this task much easier b
3 min read
Data profiling in Pandas using Python
Pandas is one of the most popular Python library mainly used for data manipulation and analysis. When we are working with large data, many times we need to perform Exploratory Data Analysis. We need to get the detailed description about different columns available and there relation, null check, data types, missing values, etc. So, Pandas profiling
1 min read
Data Manipulation in Python using Pandas
In Machine Learning, the model requires a dataset to operate, i.e. to train and test. But data doesn’t come fully prepared and ready to use. There are discrepancies like Nan/ Null / NA values in many rows and columns. Sometimes the data set also contains some of the rows and columns which are not even required in the operation of our model. In such
6 min read
10 Python Pandas tips to make data analysis faster
Data analysis using Python's Pandas library is a powerful process, and its efficiency can be enhanced with specific tricks and techniques. These Python tips will make our code concise, readable, and efficient. The adaptability of Pandas makes it an efficient tool for working with structured data. Whether you are a beginner or an experienced data sc
15 min read
Pandas Cheat Sheet for Data Science in Python
Pandas is a powerful and versatile library that allows you to work with data in Python. It offers a range of features and functions that make data analysis fast, easy, and efficient. Whether you are a data scientist, analyst, or engineer, Pandas can help you handle large datasets, perform complex operations, and visualize your results. This Pandas
15+ min read
7 Pandas Plotting Functions for Data Visualization
Data visualization is an essential component of data analysis, enabling us to acquire understanding, detect regularities, and convey discoveries efficiently. In this article, we will examine seven fundamental Pandas charting functions, including examples and explanations for each kind of plot. Types of Pandas Plotting FunctionsPandas has a range of
8 min read
Python | Pandas Working With Text Data
Series and Indexes are equipped with a set of string processing methods that make it easy to operate on each element of the array. Perhaps most importantly, these methods exclude missing/NA values automatically. These are accessed via the str attribute and generally, have names matching the equivalent (scalar) built-in string methods. In order to l
8 min read
Effective Methods for Merging Time Series Data with Metadata in Pandas
Combining time series data with metadata is a common task in data analysis, especially in fields like finance, healthcare, and IoT. This process involves merging time-indexed data with additional information that provides context or attributes to the time series. In this article, we will explore the proper way to combine time series data with metad
5 min read
Working with Missing Data in Pandas
Missing Data can occur when no information is provided for one or more items or for a whole unit. Missing Data is a very big problem in a real-life scenarios. Missing Data can also refer to as NA(Not Available) values in pandas. In DataFrame sometimes many datasets simply arrive with missing data, either because it exists and was not collected or i
11 min read
IPL 2023 Data Analysis using Pandas AI
We are already familiar with performing data analysis using Pandas, in this article, we will see how we can leverage the power of PandasAI to perform analysis on IPL 2023 Auction dataset. We have already covered the Introduction to PandasAI. You can check out our blog post here. Data Analysis using Pandas AIStep 1: Install pandasai and openai libra
6 min read
Data Visualization with Pandas
Data Visualization with Pandas is the presentation of data in a graphical format. It helps people understand the significance of data by summarizing and presenting a huge amount of data in a simple and easy-to-understand format and helps communicate information clearly and effectively. In this tutorial, we will explore how to leverage Pandas for cr
14 min read
Pandas 2.0: A Game-Changer for Data Scientists?
Pandas 2.0 introduces revolutionary features and performance improvements to the data science community! This, new version of the data manipulation and analysis tool goes to the next level with the claim of faster processing, better memory management, new API interface. Whether one is analyzing data or trying to transform it, cleaning it up, or sim
9 min read
Ethics in Data Science and Proper Privacy and Usage of Data
As we know, these days Data Science has become more popular and it is one of the emerging technologies. According to the latest estimation 328.77 million terabytes are generated every day so just think of how large the volume is. , this data may also consist of your data such as your Identity cards or your Banking information or it may be any other
8 min read
Difference Between Data Mining and Data Visualization
Data mining: Data mining is the method of analyzing expansive sums of data in an exertion to discover relationships, designs, and insights. These designs, concurring to Witten and Eibemust be "meaningful in that they lead to a few advantages, more often than not a financial advantage." Data in data mining is additionally ordinarily quantitative par
2 min read
Difference Between Data Visualization and Data Analytics
Data Visualization: Data visualization is the graphical representation of information and data in a pictorial or graphical format(Example: charts, graphs, and maps). Data visualization tools provide an accessible way to see and understand trends, patterns in data and outliers. Data visualization tools and technologies are essential to analyze massi
3 min read
Difference Between Data Science and Data Visualization
Data Science: Data science is study of data. It involves developing methods of recording, storing, and analyzing data to extract useful information. The goal of data science is to gain knowledge from any type of data both structured and unstructured. Data science is a term for set of fields that are focused on mining big data sets and discovering t
2 min read
Difference between Data Cleaning and Data Processing
Data Processing: It is defined as Collection, manipulation, and processing of collected data for the required use. It is a task of converting data from a given form to a much more usable and desired form i.e. making it more meaningful and informative. Using Machine Learning algorithms, mathematical modelling and statistical knowledge, this entire p
2 min read
Stock Data Analysis and Data Visualization with Quantmod in R
Analysis of historical stock price and volume data is done in order to obtain knowledge, make wise decisions, and create trading or investment strategies. The following elements are frequently included in the examination of stock data in the R Programming Language. Historical Price Data: Historical price data contains information about a stock's op
8 min read
Data Science: Unleashing the Power of Data For Students and Professionals
The capacity to organize and make sense of massive volumes of data has grown in value in today's data-driven society. Data science provides a plethora of information and possibilities, whether you're a student studying for a future career or a seasoned professional trying to stay competitive. This article examines the convincing arguments for why d
3 min read
Difference between a Data Analyst and a Data Scientist
Nowadays as we know the roles of Data analyst and Data scientist are often used in extracting insights from the data. Both professionals work with data to get various insights, but their responsibilities, skill sets, and the depth of their involvement in the data analytics process differ significantly. In this article, we will explore the What is D
5 min read
Operational Databases vs. Data Warehouses in Data Engineering: Key Differences and Strategic Use Cases
In the field of data management, two fundamental components play pivotal roles in organizing and leveraging data effectively: operational databases and data warehouses. While both serve as repositories for storing and managing data, they differ significantly in their structure, purpose, and functionality. In this article, we delve into the nuances
5 min read
Practice Tags :