Kodeclik Blog

How to print the first 10 records of a Pandas dataframe

Recall that a Pandas dataframe is just like a table or spreadsheet, composed of columns and rows which contain data about some subject matter. Each column denotes typically one attribute (or variable) and each row contains one instance or observation of all variables.
For instance, here is a simple Pandas dataframe where the rows denote months and columns denote various facets of months:
The output will be:
Now let us suppose you wish to print only the first 10 rows of this dataframe. Let us learn how to do so!

Method 1: Use the head() method

The first method is the easiest to apply. It simply takes an argument corresponding to the number of rows you desire, i.e., in our case 10:
The output is:
Note that this time the printed output goes only till the month of October, i.e., months 0 to 9.

Method 2: Use slicing operators

The second approach uses slicing operators like so:
The output is:
as expected. Note that slicing in Pandas, like many other things in Python, is done using the square bracket notation and allows you to select a subset of data based on a range of indices.

Method 3: Use the iloc() method

The third approach uses the iloc() method that takes two list arguments, one denoting the rows you need and the second denoting the columns you need:
Note that in our case we desire all the columns, so the second index is just “:”. The output is again:
In conclusion, these are some of the easiest and most common methods to get the first 10 records of a Pandas DataFrame. The head() function is a simple and effective way to retrieve the first n rows, while slicing and iloc() can be used to get any range of data based on your requirements. Selecting a smaller subset of data can be useful for exploring and understanding the structure of the data before performing more complex operations. By using these methods, you can quickly and easily retrieve the first 10 rows of your DataFrame and continue your data analysis. Happy coding!
Which of the methods we have discussed is your favorite?
If you liked this blogpost, checkout our post on extracting the nth row of a Pandas dataframe.
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2023. All rights reserved.