The loc[] accessor in Pandas is used to select rows and columns from a DataFrame using labels, slices, or Boolean conditions. It can be used to access individual values, select specific rows or columns, and filter data based on conditions.
import pandas as pd
df = pd.DataFrame({
"Name": ["Alice", "Bob", "Charlie"],
"Age": [20, 25, 22]
})
print(df.loc[1])
Output
Name Bob Age 25 Name: 1, dtype: object
Syntax
The loc[] accessor has the following syntax:
DataFrame.loc[row_labels, column_labels]
Parameters:
- row_labels: Specifies the row labels to select.
- column_labels: Specifies the column labels to select.
Returns: Scalar, Series, or DataFrame depending on the selection.
Example 1: Select a Single Value Using loc[]
The loc[] accessor can be used to select a specific value by providing its row and column labels.
import pandas as pd
df = pd.DataFrame({
'Weight': [45, 88, 56, 15, 71],
'Name': ['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'],
'Age': [14, 25, 55, 8, 21]
})
df.index = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']
print("Original DataFrame:")
print(df)
result = df.loc['Row_2', 'Name']
print("\nSelected Value:")
print(result)
Output
Original DataFrame:
Weight Name Age
Row_1 45 Sam 14
Row_2 88 Andrea 25
Row_3 56 Alex 55
Row_4 15 Robin 8
Row_5 71 Kia 21
Selected Value:
A...Explanation:
- df.loc['Row_2', 'Name'] selects the value at Row_2 and the Name column.
- loc[] uses labels rather than integer positions.
- The selected value is Andrea.
Example 2: Select Multiple Rows and Columns
We can use loc[] to select multiple columns while keeping all rows.
import pandas as pd
df = pd.DataFrame({
"A": [12, 4, 5, None, 1],
"B": [7, 2, 54, 3, None],
"C": [20, 16, 11, 3, 8],
"D": [14, 3, None, 2, 6]
})
df.index = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']
print("Original DataFrame:")
print(df)
result = df.loc[:, ['A', 'D']]
print("\nSelected Columns:")
print(result)
Output
Original DataFrame:
A B C D
Row_1 12.0 7.0 20 14.0
Row_2 4.0 2.0 16 3.0
Row_3 5.0 54.0 11 NaN
Row_4 NaN 3.0 3 2.0
Row_5 1.0 NaN 8 6.0
Selected Co...Explanation:
- : selects all rows.
- ['A', 'D'] selects the A and D columns.
- loc[] returns a DataFrame containing the selected columns.
Example 3: Select Rows and Columns by Label
loc[] can select a range of rows and columns using their labels.
import pandas as pd
df = pd.DataFrame({
"A": [12, 4, 5, None, 1],
"B": [7, 2, 54, 3, None],
"C": [20, 16, 11, 3, 8],
"D": [14, 3, None, 2, 6]
})
df.index = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']
selected_data = df.loc['Row_2':'Row_4', 'B':'D']
print(selected_data)
Output
B C D Row_2 2.0 16 3.0 Row_3 54.0 11 NaN Row_4 3.0 3 2.0
Explanation:
- 'Row_2':'Row_4' selects rows from Row_2 through Row_4.
- 'B':'D' selects columns from B through D.
- Label-based slicing with loc[] includes the ending label.
Example 4: Select Rows Using a Condition
loc[] can filter rows by applying a Boolean condition to a column.
import pandas as pd
df = pd.DataFrame({
"A": [12, 4, 5, None, 1],
"B": [7, 2, 54, 3, None],
"C": [20, 16, 11, 3, 8],
"D": [14, 3, None, 2, 6]
})
df.index = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']
result = df.loc[df['A'] > 5]
print(result)
Output
A B C D Row_1 12.0 7.0 20 14.0
Explanation:
- df['A'] > 5 creates a Boolean condition.
- loc[] selects the rows where the condition is True.
- Only Row_1 has a value greater than 5 in column A.
Example 5: Using Conditions with Pandas loc
The loc[] accessor can filter rows based on conditions applied to DataFrame columns. We can use it to select rows where a column meets a specific condition or contains non-null values.
import pandas as pd
df = pd.DataFrame({
"A": [12, 4, 5, None, 1],
"B": [7, 2, 54, 3, None],
"C": [20, 16, 11, 3, 8],
"D": [14, 3, None, 2, 6]
})
df.index = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']
print("Original DataFrame:")
print(df)
selected_rows = df.loc[df['A'] > 5]
print("\nRows where column 'A' is greater than 5:")
print(selected_rows)
non_null_rows = df.loc[df['B'].notnull()]
print("\nRows where column 'B' is not null:")
print(non_null_rows)
Output
Original DataFrame:
A B C D
Row_1 12.0 7.0 20 14.0
Row_2 4.0 2.0 16 3.0
Row_3 5.0 54.0 11 NaN
Row_4 NaN 3.0 3 2.0
Row_5 1.0 NaN 8 6.0
Rows where ...Explanation:
- df['A'] > 5 checks which rows have a value greater than 5 in column A.
- df.loc[df['A'] > 5] returns only the rows that satisfy this condition.
- df['B'].notnull() checks whether column B contains a non-null value.
- df.loc[df['B'].notnull()] returns the rows where column B is not null.