Movatterモバイル変換


[0]ホーム

URL:


Python Pandas Tutorial

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 PandasDataFrame.iloc[] attribute used to slice a DataFrame based on the integer position (i.e, integer-based indexing) of rows and columns.

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

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

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

Example: Slicing DataFrame Rows by Position

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

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

Following is the output of the above code −

Input DataFrame:  col1 col20    a    b1    c    d2    e    f3    g    hOutput:  col1 col21    c    d2    e    f

Slicing a DataFrame by Label

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

Following is thesyntax 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 androw_label_end are indicates the start and end labels of the DataFrame rows. Similarly,column_label_start andcolumn_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.

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

Following is the output of the above code −

Original DataFrame:   col1 col2r1    a    br2    c    dr3    e    fr4    g    hOutput:r1    ar2    cr3    eName: 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.

import pandas as pddata = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}df = pd.DataFrame(data)# Slice a single columncol_A = df.iloc[:, 0]print("Slicing a single column A using iloc[]:")print(col_A)# Slice multiple columnscols_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    11    22    3Name: A, dtype: int64Slicing multiple columns A and B using iloc[]:   A  B0  1  41  2  52  3  6

Example: Column Slicing Using loc[]

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

import pandas as pddata = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}df = pd.DataFrame(data)# Slice a single column by labelcol_A = df.loc[:, 'A']print("Slicing a single column A using loc[]:")print(col_A)# Slice multiple columns by labelcols_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    11    22    3Name: A, dtype: int64Slicing Multiple columns A and B using loc[]:   A  B0  1  41  2  52  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.

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

Following is the output of the above code −

Original DataFrame:  col1 col20    a    b1    c    d2    e    f3    g    hModified DataFrame:  col1 col20    a    b1    x    d2    y    f3    g    h
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp