- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Pandas - How to select rows from a DataFrame by passing row label
To select rows by passing a label, use the loc() function. Mention the index of which you want to select the row. This is the index label in our example. We have x, y and z as the index label and can be used to select rows with loc().
Create a DataFrame −
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]],index=['x', 'y', 'z'],columns=['a', 'b'])
Now, select rows with loc. We have passed the index label “z” −
dataFrame.loc['z']
Example
Following is the code −
import pandas as pd # Create DataFrame dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]],index=['x', 'y', 'z'],columns=['a', 'b']) # DataFrame print"DataFrame...\n",dataFrame # select rows with loc print"\nSelect rows by passing label..." print(dataFrame.loc['z'])
Output
This will produce the following output −
DataFrame... a b x 10 15 y 20 25 z 30 35 Select rows by passing label... a 30 b 35 Name: z, dtype: int64
Advertisements