1.3 Getting and displaying dataframe rows

Dataframes can have hundreds or thousands of rows, so it is not practical to display a whole dataframe.

However, there are a number of dataframe attributes and methods that allow you to get and display either a single row or a number of rows at a time. Three of the most useful methods are: and . Note that to distinguish methods and attributes, we write () after a method’s name.

An image of a data algorithm
Figure 4

The iloc attribute

A dataframe has a default integer index for its rows, which starts at 0 (zero). You can get and display any single row in a dataframe by using the attribute with the index of the row you want to access as its argument. For example, the following code will get and display the first row of data in the dataframe , which is at index 0:

df.iloc[0]

Country Afghanistan

Population (1000s) 30552

TB deaths 13000

Name: 0, dtype: object

Similarly, the following code will get and display the third row of data in the dataframe , which is at index 2:

df.iloc[2]

Country Algeria

Population (1000s) 39208

TB deaths 5100.0

Name: 0, dtype: object

The head() method

The first few rows of a dataframe can be printed out with the  method.

You can tell  is a method, rather than an attribute such as , because of the parentheses (round brackets) after the property name.

If you don’t give any argument, i.e. don’t put any number within those parentheses, the default behaviour is to return the first five rows of the dataframe. If you give an argument, it will print that number of rows (starting from the row indexed by 0).

For example, executing the following code will get and display the first five rows in the dataframe .

df.head()

 CountryPopulation (1000s)TB deaths
0Afghanistan3055213000.00
1Albania317320.00
2Algeria392085100.00
3Andorra790.26
4Angola214726900.00

And, executing the following code will get and display the first seven rows in the dataframe 

df.head(7)

 CountryPopulation (1000s)TB deaths
0Afghanistan3055213000.00
1Albania317320.00
2Algeria392085100.00
3Andorra790.26
4Angola214726900.00
5Antigua and Barbuda901.20
6Argentina41446570.00

The tail() method

The  method is similar to the method.

If no argument is given, the last five rows of the dataframe are returned, otherwise the number of rows returned is dependent on the argument, just like for the  method.

df.tail()

 CountryPopulation (1000s)TB deaths
189Venezuela (Bolivarian Republic of)30405480
190Viet Nam9168017000
191Yemen24407990
192Zambia145393600
193Zimbabwe141505700