How to Print Specific Row of Pandas DataFrame


You can use the following methods to print a specific row of a pandas DataFrame:

Method 1: Print Row Based on Index Position

print(df.iloc[[3]])

Method 2: Print Row Based on Index Label

print(df.loc[['this_label']])

The following examples show how to use each method in practice with the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [18, 22, 19, 14, 10, 11, 20, 28],
                   'assists': [4, 5, 5, 4, 9, 12, 11, 8],
                   'rebounds': [3, 9, 12, 4, 4, 9, 8, 2]},
                    index=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'])

#view DataFrame
print(df)

   points  assists  rebounds
A      18        4         3
B      22        5         9
C      19        5        12
D      14        4         4
E      10        9         4
F      11       12         9
G      20       11         8
H      28        8         2

Related: Pandas loc vs. iloc: What’s the Difference?

Example 1: Print Row Based on Index Position

The following code shows how to print the row located at index position 3 in the DataFrame:

#print row located at index position 3
print(df.iloc[[3]])

   points  assists  rebounds
D      14        4         4

Notice that only the row located at index position 3 is printed.

To print multiple specific rows by index position, simply include multiple values in the iloc function:

#print rows located at index positions 3 and 5
print(df.iloc[[3, 5]])

   points  assists  rebounds
D      14        4         4
F      11       12         9

Notice that only the rows located at index positions 3 and 5 are printed.

Example 2: Print Row Based on Index Label

The following code shows how to print the row with an index label of ‘C’ in the DataFrame:

#print row with index label 'C'
print(df.loc[['C']])

   points  assists  rebounds
C      19        5        12

Notice that only the row with an index label of ‘C’ is printed.

To print multiple specific rows by index labels, simply include multiple labels in the loc function:

#print rows with index labels 'C' and 'F'
print(df.loc[['C', 'F']])

   points  assists  rebounds
C      19        5        12
F      11       12         9

Notice that only the rows with index labels ‘C’ and ‘F’ are printed.

Additional Resources

The following tutorials explain how to perform other common operations in pandas:

How to Print Pandas DataFrame with No Index
How to Print One Column of a Pandas DataFrame
How to Show All Rows of a Pandas DataFrame

Leave a Reply

Your email address will not be published. Required fields are marked *