Slicing Pandas Dataframe

Last Updated : 14 Apr, 2026

Slicing a Pandas DataFrame is an important skill for extracting specific data subsets. Whether selecting rows, columns or individual cells, Pandas provides efficient methods such as iloc[] and loc[]. It focuses on using integer-based and label-based indexing to slice DataFrames effectively.

Create a Custom Dataframe

Let's import pandas library and create pandas dataframe from custom nested list.

Python
import pandas as pd

player_list = [['M.S.Dhoni', 36, 75, 5428000],
               ['A.B.D Villers', 38, 74, 3428000],
               ['V.Kohli', 31, 70, 8428000],
               ['S.Smith', 34, 80, 4428000],
               ['C.Gayle', 40, 100, 4528000],
               ['J.Root', 33, 72, 7028000],
               ['K.Peterson', 42, 85, 2528000]]

df = pd.DataFrame(player_list, columns=['Name', 'Age', 'Weight', 'Salary'])
print(df) 

Output:

creating_custom_dataframe

Slicing Using iloc[] (Integer-Based Indexing)

The iloc[] method in Pandas allows us to extract specific rows and columns based on their integer positions starting from 0. Each number represents a position in the DataFrame not the actual label of the row or column.

Slicing Rows in dataframe

Row slicing means selecting a specific set of rows from the DataFrame while keeping all columns.

Python
df1 = df.iloc[0:4]
print(df1)

Output:

slicing_using_iloc

Slicing Columns in dataframe

Column slicing means selecting a specific set of columns from the DataFrame while keeping all rows.

Python
df1 = df.iloc[:, 0:2]

print(df1)

Output:

slicing_columns

Selecting a Specific Cell in a Pandas DataFrame

If you need a single value from a DataFrame you can specify the exact row and column position

Python
value = df.iloc[2, 3]  
print("Specific Cell Value:", value)

Output:

Specific Cell Value: 8428000

Using Boolean Conditions in a Pandas DataFrame

Instead of selecting rows by index we can use Boolean conditions (e.g., Age > 35) to filter rows dynamically.

Python
data = df[df['Age'] > 35]
print("\nFiltered Data based on Age > 35:\n", data)

Output:

Screenshot-2025-03-15-095646

Slicing Using loc[]

Slicing can also be performed using the loc[] function in Pandas. Since loc[] is label-based, it selects data using row and column labels. As a result, when working with custom indices, it is important to reference the correct labels during selection.

Slicing Rows in Dataframe

With loc[] we can extract a range of rows by their labels instead of integer positions.

Python
df.set_index('Name', inplace=True)

custom = df.loc['A.B.D Villers':'S.Smith']
print(custom)

Output:

slicing_using_loc

Selecting Specified cell in Dataframe

loc[] allows us to fetch a specific value based on row and column labels

Python
value = df.loc['V.Kohli', 'Salary']
print("\nValue of the Specific Cell (V.Kohli, Salary):", value)

Output:

Value of the Specific Cell (V.Kohli, Salary): 8428000

Comment

Explore