How to print index

Here are tips on how to print index in Pandas.
how to print row in pandas

This is easy to print a column. But how to print a row in Pandas?

How to print index with loc

To access a row using loc function you need to use a row index label as an argument.

import pandas as pd

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

print(my_df.loc[['indexB']])

Output:

       Column1 Column2 Column3
indexB       4       6      10

How to print index with iloc

To access a row using loc function you need to use a row index position as an argument.

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]])

Output:

  Column1 Column2 Column3
2       3       2      43

Outputs are the same.

This Post Has 4 Comments

Leave a Reply