In this tutorial, we’ll look at how to select the first n rows of a pandas dataframe.
If you prefer a video tutorial over text, check out the following video detailing the steps in this tutorial –
How to select the first n rows?
You can use the pandas dataframe head()
function and pass n as a parameter to select the first n rows of a dataframe. Alternatively, you can slice the dataframe using iloc
to select the first n rows. The following is the syntax:
# select first n rows using head()df.head(n)# select first n rows using ilocdf.iloc[:n,:]
The two methods above return a dataframe with only the first n rows of the original dataframe.
Examples
Let’s look at some examples of using the above methods to select first n rows. First, we’ll create a sample dataframe that we’ll be using throughout this tutorial:
Highlighted programs for you
Important information for students×
Put simply, All Star is in the business of connecting students and schools.We help students find schools that are great matches for their educationalneeds, personal preferences and lifestyles, and schools pay us for our work.
Here's a quick Q & A of information we think you should know if you chooseto use our websites. The main takeaways: Using our services is free, butstarting and completing a degree, certificate or diploma program takescommitment and effort and should be considered carefully.
1. How do you provide your services for free?
Schools pay to advertise on our sites. This allows us to offer our serviceto prospective students like you for free.
Schools place a very high priority on enrolling students who go on tograduate. By using All Star's focused, information-rich services, schoolscan be more confident that the prospective students we introduce them to aretruly committed to their education and to succeeding once they're enrolledin school.
2. How do you differ from your competitors?
There are other companies out there that do what we do. But there is no onethat does it with more integrity or respect for our users and their choices.We put you, the student, in control. You get to choose the schools you'reinterested in, and you get to choose what programs you'd like to learn moreabout. We will never submit your contact information to a school withoutyour consent.
3. Do you really work with ALL schools?
No. Our listings are not exhaustive, we do not list all schools, but they doinclude a rich selection of options. We believe this wide variety of optionsfrom hundreds of schools meets the needs of most prospective students whovisit our sites. We partner with smaller schools that specialize in oneparticular career field, such as Pima Medical Institute, as well asworld-class, multi-discipline institutions like the University of SouthernCalifornia.
4. Is getting a degree really going to open up doors for me?
We really want you to succeed in the program you choose. So does yourschool. But we feel compelled to be very frank and upfront: You must workhard and stay committed to graduate. And assuming you do graduate, there isno guarantee you will find a job in your chosen field, or any job for thatmatter.
Obtaining an education has many personal benefits and can also improve yourfinancial prospects. However, it's important to keep in mind that obtainingan education does not guarantee financial success or even a job. Job marketsvary greatly by region, state, and even locally, and are affected by trendsin the national economy and even international events. Other factorsaffecting your job-hunting success may include your job history andexperience, and your level of education, degree, or certificate type. Yourarea of specialization plays a role, too.
5. If I do find a job, what can I expect in terms of salary?
The government publishes a great deal of information related to hundreds ofjobs on the Bureau of Labor Statistics (BLS) website. We use this as aresource for many of the articles on the All Star websites. As comprehensiveas the BLS information is, it is neither complete nor entirely accurate. TheBLS salary information we publish is a national average. Actual salaries fora particular job or skill may be different where you live. For example, ifyou live in a large city or where the job market for particular skills isespecially competitive, such as Silicon Valley in California, you're likelyto receive a higher wage or salary for the same job than you would in arural or economically depressed market. Other factors that can affect salaryrates include the size of the employer, union contracts and governmentalregulations to name a few.
6. Where are you located? How can I contact you?
All Star Directories is located at P.O. Box 1677 Renton, WA 98057. You canreach us at (206) 436-7500 or at customerservice@allstardirectories.com.
University of Maryland Global Campus
University of Maryland Global Campus
Cloud Computing Systems Master's
Digital Forensics & Cyber Investigation Master's
import pandas as pd# dataframe of height and weight football playersdf = pd.DataFrame({ 'Height': [167, 175, 170, 186, 190, 188, 158, 169, 183, 180], 'Weight': [65, 70, 72, 80, 86, 94, 50, 58, 78, 85], 'Team': ['A', 'A', 'B', 'B', 'B', 'B', 'A', 'A', 'B', 'A']})# display the dataframeprint(df)
Output:
Height Weight Team0 167 65 A1 175 70 A2 170 72 B3 186 80 B4 190 86 B5 188 94 B6 158 50 A7 169 58 A8 183 78 B9 180 85 A
The above dataframe contains the height (in cm) and weight (in kg) data of football players from two teams, A and B.
1. Select first n rows using head()
To select the first n rows using the pandas dataframe head()
function. Pass n, the number of rows you want to select as a parameter to the function. For example, to select the first 3 rows of the dataframe df:
print(df.head(3))
Output:
Height Weight Team0 167 65 A1 175 70 A2 170 72 B
Here, the head() function returned the first three rows of the dataframe df. Note that, by default, the head() function returns the first five rows if n is not specified.
print(df.head())
Output:
Height Weight Team0 167 65 A1 175 70 A2 170 72 B3 186 80 B4 190 86 B
Fore more on the pandas head() function, refer to its documentation.
2. Select first n rows using iloc
You can also select the first n rows of a dataframe by slicing it on index using iloc
. For example, to slice the first three rows of the dataframe df:
print(df.iloc[:3,:])
Output:
Height Weight Team0 167 65 A1 175 70 A2 170 72 B
Here, we specify the row and column indices we want to select using iloc. Note that, in df.iloc[:3,:]
the first slice :3
is used to select all the rows from starting till (but not including) the row with index 3 (that is, rows with index 0, 1, and 2) and the second slice :
is used to select all the columns.
For more, refer to pandas’guideon indexing and selecting data.
With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in aJupyter Notebookwith a python (version 3.8.3) kernel having pandas version 1.0.5
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
-
Piyush Raj
Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.