Python Pandas - Slicing a DataFrame Object



Pandas DataFrame slicing is a process of extracting specific rows, columns, or subsets of data based on both position and labels. DataFrame slicing is a common operation while working with large datasets, it is similar to Python lists and NumPy ndarrays, DataFrame slicing uses the [] operator and specific slicing attributes like .iloc[] and .loc[] to retrieve data efficiently.

In this tutorial, we will learn about how to slice Pandas DataFrames using both positional and label-based indexing.

Introduction to Pandas DataFrame Slicing

Pandas DataFrame slicing is performed using two main attributes, which are −

  • .iloc[]: For slicing based on position (integer-based indexing).

  • .loc[]: For slicing based on labels (index labels or column labels).

Let's learn about all possible ways of slicing a Pandas DataFrame.

Slicing a DataFrame by Position

The Pandas DataFrame.iloc[] attribute used to slice a DataFrame based on the integer position (i.e, integer-based indexing) of rows and columns.

Following is the syntax of slicing a DataFrame using the .iloc[] attribute −

DataFrame.iloc[row_start:row_end, column_start:column_end]

Where, row_start and row_end are indicates the start and end integer-based index values of the DataFrame rows. Similarly, column_start and column_end are the column index values.

Example: Slicing DataFrame Rows by Position

The following example demonstrates how to slice the DataFrame rows using the DataFrame.iloc[] attribute.

Open Compiler
import pandas as pd # Create a Pandas DataFrame df = pd.DataFrame([['a','b'], ['c','d'], ['e','f'], ['g','h']], columns=['col1', 'col2']) # Display the DataFrame print("Input DataFrame:") print(df) # Slice rows based on position result = df.iloc[1:3, :] print("Output:") print(result)

Following is the output of the above code −

Input DataFrame:
  col1 col2
0    a    b
1    c    d
2    e    f
3    g    h

Output:
  col1 col2
1    c    d
2    e    f

Slicing a DataFrame by Label

The Pandas DataFrame.loc[] attribute used to slice a DataFrame based on the labels of rows and columns.

Following is the syntax of slicing a DataFrame using the .loc[] attribute −

DataFrame.loc[row_label_start:row_label_end, column_label_start:column_label_end]

Where, row_label_start and row_label_end are indicates the start and end labels of the DataFrame rows. Similarly, column_label_start and column_label_end are the column labels.

Example: Slicing DataFrame Rows and Columns using .loc[]

The following example demonstrates how to slice a DataFrame rows and columns by using their labels with the .loc[] attribute.

Open Compiler
import pandas as pd # Create a DataFrame with labeled indices df = pd.DataFrame([['a','b'], ['c','d'], ['e','f'], ['g','h']], columns=['col1', 'col2'], index=['r1', 'r2', 'r3', 'r4']) # Display the DataFrame print("Original DataFrame:") print(df) # Slice rows and columns by label result = df.loc['r1':'r3', 'col1'] print("Output:") print(result)

Following is the output of the above code −

Original DataFrame:
   col1 col2
r1    a    b
r2    c    d
r3    e    f
r4    g    h

Output:
r1    a
r2    c
r3    e
Name: col1, dtype: object

DataFrame Column Slicing

Similar to the above row slicing, Pandas DataFrame Column slicing can also done using the .iloc[] for position and .loc[] for labels.

Example: Column Slicing using iloc[]

The following example slice the DataFrame columns based on their integer position.

Open Compiler
import pandas as pd data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]} df = pd.DataFrame(data) # Slice a single column col_A = df.iloc[:, 0] print("Slicing a single column A using iloc[]:") print(col_A) # Slice multiple columns cols_AB = df.iloc[:, 0:2] print("Slicing multiple columns A and B using iloc[]:") print(cols_AB)

Following is the output of the above code −

Slicing a single column A using iloc[]:
0    1
1    2
2    3
Name: A, dtype: int64

Slicing multiple columns A and B using iloc[]:
   A  B
0  1  4
1  2  5
2  3  6

Example: Column Slicing Using loc[]

This example slices the DataFrame columns by their labels using the .loc[] attribute.

Open Compiler
import pandas as pd data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]} df = pd.DataFrame(data) # Slice a single column by label col_A = df.loc[:, 'A'] print("Slicing a single column A using loc[]:") print(col_A) # Slice multiple columns by label cols_AB = df.loc[:, 'A':'B'] print("Slicing Multiple columns A and B using loc[]:") print(cols_AB)

Following is the output of the above code −

Slicing a single column A using loc[]:
0    1
1    2
2    3
Name: A, dtype: int64

Slicing Multiple columns A and B using loc[]:
   A  B
0  1  4
1  2  5
2  3  6

Modifying Values After Slicing

After slicing a DataFrame, you can modify the sliced values directly. This can be done by assigning new values to the selected elements.

Example

This example demonstrates how to modify the sliced DataFrame values directly.

Open Compiler
import pandas as pd # Create a DataFrame df = pd.DataFrame([['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']], columns=['col1', 'col2']) # Display the Original DataFrame print("Original DataFrame:", df, sep='\n') # Modify a subset of the DataFrame using iloc df.iloc[1:3, 0] = ['x', 'y'] # Display the modified DataFrame print('Modified DataFrame:',df, sep='\n')

Following is the output of the above code −

Original DataFrame:
  col1 col2
0    a    b
1    c    d
2    e    f
3    g    h

Modified DataFrame:
  col1 col2
0    a    b
1    x    d
2    y    f
3    g    h
Advertisements