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
Updated on: 2021-09-16T09:12:58+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements