Home »
Python »
Python Programs
Select Pandas rows based on list index
Given a Pandas DataFrame, we have to select rows based on list index.
By Pranit Sharma Last updated : September 22, 2023
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and the data.
Selecting pandas rows based on list index
When it comes to selecting a row or column value, we always use pandas.DataFrame.loc property or pandas.DataFrame.iloc property. To select pandas rows based on the list index, we will select an index of those rows with certain sequence numbers which indicate a list. If we want row 1 and row 3 as a list, then we will pass [1,3] in a list and then we will select all columns by using ':'.
Note
To work with pandas, we need to import pandas package first, below is the syntax:
import pandas as pd
Let us understand with the help of an example,
Python program to select Pandas rows based on list index
# Importing pandas package
import pandas as pd
# Creating a DataFrame
df = pd.DataFrame({
'Brand':['Samsung','Motorola','Redmi'],
'Series':['M','E','A'],
'Price_range':['15k-25k','10k-20k','10k-15k']
})
# Display DataFrame
print("Created DataFrame\n",df,"\n")
# Selecting row based on list
ind_list = [0, 2]
result = df.iloc[ind_list]
print("Selected rows:\n",result)
Output
The output of the above program is:
Python Pandas Programs »