pandas: iloc
and loc
in Pandas#
import pandas as pd
Loading data into Pandas DataFrame#
The dataset is from Kaggle - Pokemon.
data = pd.read_csv('data/Pokemon.csv')
data
iloc
#
# Read single row
data.iloc[3]
# Read multiple rows
data.iloc[[3,6]]
# Read a range of rows
data.iloc[3:7]
loc
#
The loc
property in Pandas is used to access a group of rows and columns by labels or a boolean array. Unlike iloc
, which uses integer-based indexing, loc
uses the actual labels of the index and columns. This makes it very useful for selecting data based on meaningful row or column names.
data.loc[data['Legendary'] == True].head()
If you have a condition to filter rows, then you must pass the columns that you want to select after the comma as a sequence. e.g., [condition, ['col1', 'col2']]
data.loc[data['Attack'] == 49, ['Name']]