How to print a row

Here’s the tutorial on how to print a row in Pandas.

This post will teach you how to print the row you need and which Pandas function can be used to print the row by the index number.

How to print chosen row in Pandas

Let’s assume you’d like to print the third row. How would you do that?

To print a row by index use loc Pandas function. Chosen row will be printed after using such a Python code:

print(df.iloc[[index]])

To print the second row put the index of 2.

import pandas as pd

my_df = pd.DataFrame(
    {'Column1': ['1', '4', '3', '4'],
     'Column2': ['5', '6', '2', '2'],
     'Column3': ['33', '10', '43', '12']})

print(my_df.loc[[2]])

The output:

  Column1 Column2 Column3
2       3       2      43

Using iloc function

Pandas also provides the `iloc` function to select rows by integer position. This function is similar to `loc`, but it takes integer indices instead of labels.

To print a row by index using `iloc`, we can use the following code:

import pandas as pd

my_df = pd.DataFrame(
    {'Column1': ['1', '4', '3', '4'],
     'Column2': ['5', '6', '2', '2'],
     'Column3': ['33', '10', '43', '12']})

print(my_df.iloc[[2]])

print(my_df.iloc[[-1]])

We can also use `iloc` to select multiple rows by passing a list of indices to the function. For example, the following code will print the first and third rows of the DataFrame:

print(my_df.iloc[[0, 2]])

Which function to use, loc or iloc, depends on your specific needs. If you know the row labels, then using loc is more efficient. However, if you only know the row positions, then you must use iloc.

Using loc function

You can easily select multiple rows by passing a list of indices or labels to the loc function. For example, to print the first and third rows of a DataFrame, you can do the following:

import pandas as pd

my_df = pd.DataFrame(
    {'Column1': ['1', '4', '3', '4'],
     'Column2': ['5', '6', '2', '2'],
     'Column3': ['33', '10', '43', '12']})

print(my_df.loc[[0, 2]])

Both loc and iloc allow you to specify a list of indices to select multiple rows at once.

To get to know more check the loc function documentation.

Leave a Reply