About Lesson
Accessing specific elements in a DataFrame is simple and flexible.
1. Selecting Columns
You can select a single column by using its name as the key.
print(df['Name']) # Access the 'Name' column
To select multiple columns:
print(df[['Name', 'City']]) # Select multiple columns
2. Selecting Rows by Index
You can access a specific row using the iloc
(index location) or loc
(label-based) method.
# Using loc (label-based indexing)
print(df.loc[1]) # Access the second row
# Using iloc (integer-location based indexing)
print(df.iloc[1]) # Also accesses the second row
3. Selecting Specific Values
To access a specific value, you can combine .loc
or .iloc
with column names:
# Using loc for label-based indexing
print(df.loc[1, 'City']) # Value at second row, 'City' column
# Using iloc for integer-based indexing
print(df.iloc[1, 2]) # Value at second row, third column