Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Pandas - How to select rows from a DataFrame by passing row label
To select rows by passing a label, use the loc[] accessor in Pandas. You can specify the index label to retrieve specific rows from a DataFrame. The loc[] accessor is label-based and allows you to select data by row and column labels.
Creating a DataFrame with Custom Index Labels
First, let's create a DataFrame with custom index labels ?
import pandas as pd
# Create DataFrame with custom index labels
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]],
index=['x', 'y', 'z'],
columns=['a', 'b'])
print("DataFrame:")
print(dataFrame)
DataFrame:
a b
x 10 15
y 20 25
z 30 35
Selecting a Single Row by Label
Use loc[] with the index label to select a specific row ?
import pandas as pd
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]],
index=['x', 'y', 'z'],
columns=['a', 'b'])
# Select row with label 'z'
selected_row = dataFrame.loc['z']
print("Selected row 'z':")
print(selected_row)
print("\nData type:", type(selected_row))
Selected row 'z': a 30 b 35 Name: z, dtype: int64 Data type: <class 'pandas.core.series.Series'>
Selecting Multiple Rows by Labels
You can also select multiple rows by passing a list of labels ?
import pandas as pd
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]],
index=['x', 'y', 'z'],
columns=['a', 'b'])
# Select multiple rows
selected_rows = dataFrame.loc(['x', 'z'])
print("Selected rows 'x' and 'z':")
print(selected_rows)
print("\nData type:", type(selected_rows))
Selected rows 'x' and 'z':
a b
x 10 15
z 30 35
Data type: <class 'pandas.core.frame.DataFrame'>
Key Points
-
loc[]uses square brackets, not parentheses likeloc() - Selecting a single row returns a Series
- Selecting multiple rows returns a DataFrame
- Index labels must exist in the DataFrame, otherwise a
KeyErroris raised
Conclusion
Use dataFrame.loc['label'] to select rows by index labels in Pandas. This method is intuitive and allows both single and multiple row selection using label-based indexing.
Advertisements
