pandas
  1. pandas-loc-vs-iloc

loc vs iloc - ( Pandas Data Operations and Processing )

Heading h2

Syntax

# loc - label based indexing
data.loc[row_label, col_label]

# iloc - integer based indexing
data.iloc[row_index, col_index]

Example

import pandas as pd

data = pd.DataFrame({ 'city': ['New York', 'Paris', 'Tokyo'],
                      'population': [8537673, 2148327, 13929286],
                      'country': ['USA', 'France', 'Japan'] })

# using loc to select data by label
selected_data = data.loc[1:2, ['population', 'country']]

# using iloc to select data by integer index
selected_data = data.iloc[1:3, 1:3]

Output

The selected_data variable contains the selected data as a Pandas DataFrame object.

Explanation

Pandas is a powerful library for data analysis and processing in Python. It provides two main indexing methods for selecting data from a Pandas DataFrame - loc and iloc.

loc is a label-based indexing method that uses row and column labels to select data from a DataFrame. It is inclusive of the last label in the range specified.

iloc is an integer-based indexing method that uses row and column indices to select data from a DataFrame. It is exclusive of the last index in the range specified.

In the above example, we create a simple Pandas DataFrame containing information about three cities. We then use the loc method to select data using column labels and the iloc method to select data using integer indices.

Use

The loc and iloc methods are used for selecting data from a Pandas DataFrame. They provide a flexible and powerful way to slice and select data based on labels or integer indices.

Important Points

  • Pandas provides two indexing methods for selecting data from a DataFrame - loc and iloc
  • loc uses row and column labels to select data, while iloc uses integer indices
  • loc is inclusive of the last label in the range specified, while iloc is exclusive of the last index in the range specified
  • Both loc and iloc return a Pandas DataFrame object

Summary

In conclusion, Pandas provides the loc and iloc methods for selecting data from a DataFrame based on labels or integer indices. These methods are powerful and flexible, and can be used in a variety of data analysis and processing applications.

Published on: