Home »
Python »
Python Programs
How to select rows in a DataFrame between two values in Python Pandas?
Given a Pandas DataFrame, we have to select rows in a DataFrame between two values.
Submitted by Pranit Sharma, on June 27, 2022
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mainly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consists of rows, columns, and the data.
Pandas Rows
Rows in pandas are the different cell (column) values that are aligned horizontally and also provide uniformity. Each row can have the same or different value. Rows are generally marked with the index number but in pandas, we can also assign index names according to the needs. In pandas, we can create, read, update and delete a column or row value.
Select Pandas rows in a DataFrame between two values
To select rows in a DataFrame between two values, we will use the name of a column and the between() method inside which we will pass the range i.e., the lower value and the higher value.
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 rows in a DataFrame between two values
# Importing pandas package
import pandas as pd
# Importing reduce function
from functools import reduce
# Creating DataFrames
df = pd.DataFrame({
'Name':['Hari','Om','Rakesh','Mohan','Shilpi','Monica'],
'Age':[24,25,33,29,27,26],
'Salary':[19000,33000,94000,75000,67000,50000]
})
# Display DataFrame
print("Created DataFrame:\n",df,"\n")
# Selecting a row where which lies be a
# particular range
result = df[df['Salary'].between(40000, 100000)]
# Display Result
print("Winner:\n",result)
Output:
Python Pandas Programs »