pandas
  1. pandas-dataframeloc

DataFrame.loc[] - ( Pandas Data Operations and Processing )

Heading h2

Syntax

DataFrame.loc[row_indexer, column_indexer]

Example

import pandas as pd

data = {'name': ['John', 'Jack', 'Alice', 'Bob'], 
        'age': [24, 32, 19, 45], 
        'gender': ['M', 'M', 'F', 'M']}

df = pd.DataFrame(data)
df.set_index('name', inplace=True)

# selecting a row using loc
john_info = df.loc['John']

print(john_info)

Output

age       24
gender     M
Name: John, dtype: object

Explanation

DataFrame.loc[] is a Pandas method that is used to access a group of rows and columns by labels or a boolean array.

In the above example, we create a Pandas DataFrame with three columns name, age, and gender. We then set the index of the DataFrame to the name column using the set_index() method.

We then use df.loc['John'] to select a row of data for the person with the name 'John'. This returns a Pandas series object with the age and gender columns for the person with the name 'John'.

Use

DataFrame.loc[] is a powerful method in Pandas that allows users to select rows and columns of data by labels. This method can be used to filter, slice, and manipulate data in a Pandas DataFrame with great flexibility.

Important Points

  • DataFrame.loc[] is used to access a group of rows and columns by labels or a boolean array
  • It takes in a row indexer and a column indexer
  • It returns a Pandas series or DataFrame object depending on the input

Summary

In conclusion, DataFrame.loc[] is a useful method in Pandas that allows users to access a group of rows and columns by labels. It can be used to filter, slice, and manipulate data in a Pandas DataFrame with great flexibility. The method returns a Pandas series or DataFrame object depending on the input.

Published on: