Learn Before
Concept

Pandas DataFrame .loc Slicing

.loc is label based, so you must use the row or column labels to access the data.

Given the pictured dataframe,

If you want to access all of the “viper” values you would run...

df.loc["viper"]

This returns a Pandas Series of the “viper” row.

If you want to extract multiple rows, you can include all of the row names in a list like...

df.loc[["cobra", "viper"]]

This returns a Pandas DataFrame of all of the values from both the “cobra” and “viper” rows.

To get a single value such as the max_speed of a sidewinder, you can use...

df.loc["sidewinder", "max_speed"]

This would return a single integer value of 7.

The syntax for the above example is...

df.loc[row_name, column_name]
Image 0

0

1

Updated 2021-05-19

Tags

Python Programming Language

Data Science