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

Indexing and Selecting Data with Pandas

Last Updated : 04 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Indexing in Pandas refers to selecting specific rows and columns from a DataFrame. It allows you to subset data in various ways, such as selecting all rows with specific columns, some rows with all columns, or a subset of both rows and columns. This technique is also known as Subset Selection.

Let’s learn how to use different techniques for indexing and selecting data with Pandas.

Indexing Data using the [] Operator

The most straightforward way to index data in Pandas is by using the [] operator. This method can be used to select individual columns or multiple columns.

Selecting a Single Column

To select a single column, you simply reference the column name inside square brackets:

Python
import pandas as pd

# Load the data
data = pd.read_csv("nba.csv", index_col="Name")
print("Dataset")
display(data.head(5))

# Select a single column
first = data["Age"]
print("\nSingle Column selected from Dataset")
display(first.head(5))

Output:

Single-Column-selected-from-the-Dataset

Selecting Multiple Columns

To select multiple columns, pass a list of column names:

Python
first = data[["Age", "College", "Salary"]]
print("\nMultiple Columns selected from Dataset")
display(first.head(5))  

Output:

Multiple-columns-selected


Pandas offers several indexing methods to efficiently extract elements, rows, and columns from a DataFrame. These methods, while similar, have distinct behaviors. The four main types of indexing in Pandas are:

  1. DataFrame[]: Known as the indexing operator, used for basic selection.
  2. DataFrame.loc[]: Label-based indexing for selecting data by row/column labels.
  3. DataFrame.iloc[]: Position-based indexing for selecting data by row/column integer positions.

Together, these indexing methods, also called “indexers,” are the most common ways to access data in a Pandas DataFrame.

Indexing a DataFrame using .loc[ ]

The .loc[] function in Pandas is used for selecting data by row and column labels. Unlike the indexing operator, .loc[] can select subsets of rows and columns simultaneously, offering flexibility in data retrieval.

Selecting a single row

To select a single row, provide the row label inside the .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

For multiple rows, pass a list of row labels to .loc[]:

Python
# Select multiple rows
first = data.loc[["Avery Bradley", "R.J. Hunter"]]
display(first)

Output:

Selecting Specific Rows and Columns

To select specific rows and columns, provide both row labels and column names as lists:

Dataframe.loc[["row1", "row2"], ["column1", "column2", "column3"]]
Python
# Select two rows and three columns
first = data.loc[["Avery Bradley", "R.J. Hunter"], ["Team", "Number", "Position"]]
print(first)

Output:

Selecting all of the rows and some columns

To select all rows and specific columns, use a colon [:] to indicate all rows, followed by the list of column names:

Dataframe.loc[:, ["column1", "column2", "column3"]]
Python
# Select all rows and specific columns
first = data.loc[:, ["Team", "Number", "Position"]]
print(first)

Output:

The .loc[] method in Pandas offers a powerful way to index and filter data using labels, making it a core tool for data selection.

Indexing a DataFrame using .iloc[ ]

The .iloc[] function in Pandas allows data selection based on integer positions (rather than labels). It is similar to .loc[], but only accepts integer-based indices to specify rows and columns.

Selecting a Single Row

To select a single row using .iloc[], provide the integer position of the row:

Python
import pandas as pd
data = pd.read_csv("nba.csv", index_col="Name")

# Select a single row by position
row2 = data.iloc[3]
print(row2)

Output:

Selecting Multiple Rows

To select multiple rows, pass a list of integer positions:

Python
# Select multiple rows by position
row2 = data.iloc[[3, 5, 7]]
display(row2)

Output:

Selecting Specific Rows and Columns

To select specific rows and columns, provide integer positions for both rows and columns:

Python
# Select two rows and two columns by position
row2 = data.iloc[[3, 4], [1, 2]]
print(row2)

Output:

Selecting All Rows and Some Columns

To select all rows and specific columns, use a colon [:] for all rows and a list of column positions:

Python
# Select all rows and specific columns
row2 = data.iloc[:, [1, 2]]
print(row2)

Output:

The .iloc[] method is a powerful way to select data by position, offering flexibility in accessing subsets of a DataFrame based on integer indexing.

Other methods for indexing in a Pandas DataFrame include:

deprecated ones:

FunctionDescription
DataFrame.head()Return top n rows of a DataFrame.
DataFrame.tail()Return bottom n rows of a DataFrame.
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.lookup()Label-based “fancy indexing” function for DataFrame.
DataFrame.pop()Return item and drop from DataFrame.

DataFrame.xs()

Return a cross-section (row(s) or column(s)) from the DataFrame.
DataFrame.get()Get item from object for given key (e.g., DataFrame column).
DataFrame.isin()Return a boolean DataFrame showing whether each element is contained in values.
DataFrame.where()Return an object of the same shape with entries from self where cond is True, otherwise from other.
DataFrame.mask()Return an object of the same shape with entries from self where cond is False, otherwise from other.
DataFrame.query()Query the columns of a DataFrame with a boolean expression.
DataFrame.insert()Insert a column into DataFrame at a specified location.

This table contains only active, non-deprecated methods for DataFrame indexing in Pandas. Let me know if you need more details!

Indexing and Selecting Data with Pandas – FAQs

What is indexing and selecting data with Pandas in Python?

Indexing and selecting data in Pandas refer to the methods used to access or modify specific rows and columns in a DataFrame or Series. This can be done using label indexing, integer indexing, or condition-based filtering.

How to select data based on index in Pandas?

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

  • loc: For label-based indexing (selects data by row labels and column names).
  • iloc: For integer-based indexing (selects data by row and column positions).

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?

An indexing method defines how data is organized and accessed within a structure like a DataFrame or Series. It determines the efficiency of data retrieval and manipulation.



Next Article

Similar Reads

three90RightbarBannerImg