Are you interested in printing the first 10 rows from a Pandas dataframe? In this Python blog, I will tell you how to print first 10 rows from a Pandas dataframe in Python using different methods with some illustrative examples.
To print the first 10 rows from a Pandas DataFrame in Python, we can utilize several methods like The head() method for straightforward extraction, index slicing for Pythonic simplicity, the iloc method for positional indexing, looping through rows for custom conditions, the query() method for conditional selection, and the tail() method with negative indexing for a unique approach.
Print First 10 Rows from a Pandas DataFrame in Python
There are six different ways to print first 10 rows from a Pandas dataframe in Python.
- The head() Method
- Index Slicing
- The iloc Method
- Looping Through Rows
- Using query() Method
- The tail() Method with Negative Indexing
Let’s see them one by one using some examples:
1. Pandas dataframe print first 10 rows using the head() method
The df.head() method is a straightforward way to display the first few rows of a DataFrame in Python. We can adjust how many rows to display by specifying a number, with 10 in this case.
Here is the code to print first 10 rows from a Pandas dataframe in Python:
import pandas as pd
stock_data = {
'Date': pd.date_range(start='2023-01-01', periods=50),
'SP500_Close': [round(2800 + i * 10 + (i ** 2) / 10, 2) for i in range(50)],
'NASDAQ_Close': [round(7000 + i * 15 + (i ** 2) / 8, 2) for i in range(50)]
}
stock_df = pd.DataFrame(stock_data)
print(stock_df.head(10))
Output:
Date SP500_Close NASDAQ_Close
0 2023-01-01 2800.0 7000.00
1 2023-01-02 2810.1 7015.12
2 2023-01-03 2820.4 7030.50
3 2023-01-04 2830.9 7046.12
4 2023-01-05 2841.6 7062.00
5 2023-01-06 2852.5 7078.12
6 2023-01-07 2863.6 7094.50
7 2023-01-08 2874.9 7111.12
8 2023-01-09 2886.4 7128.00
9 2023-01-10 2898.1 7145.12
After running the code in Pycharm, the resulting output is depicted in the screenshot below.
2. How to get first n rows of dataframe Pandas using index slicing
Index slicing uses Python list-slicing syntax to select a range of rows. For the first 10 rows, we’d use df[:10], which is intuitive for those familiar with Python slicing.
This is the way we can print first 10 rows from a Pandas dataframe in Python:
import pandas as pd
import numpy as np
states = ['New York', 'California', 'Texas', 'Florida', 'Illinois']
population_data = {
'State': np.random.choice(states, 50),
'Population': np.random.randint(100000, 10000000, size=50)
}
demographics_df = pd.DataFrame(population_data)
first_10_rows = demographics_df[:10]
print(first_10_rows)
Output:
State Population
0 Florida 6484203
1 California 6992547
2 Florida 5952605
3 Florida 3770151
4 Texas 179483
5 Florida 3182736
6 Texas 1453306
7 Illinois 1437391
8 Florida 8923703
9 New York 9504386
Displayed below is a screenshot capturing the output after the code’s implementation in the Pycharm editor.
3. Print first 10 rows of dataframe using the iloc method
The iloc method in Python is used for integer-location-based indexing. To get the first 10 rows, we would use df.iloc[0:10, :], where 0:10 represents row indices and : includes all columns.
This way we can use the iloc() method to print first 10 rows from a Pandas dataframe in Python:
import pandas as pd
import numpy as np
cities = ['New York City', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix']
weather_data = {
'City': np.random.choice(cities, 50),
'Temperature (F)': np.random.randint(30, 100, size=50),
'Humidity (%)': np.random.randint(30, 80, size=50)
}
weather_df = pd.DataFrame(weather_data)
first_10_rows = weather_df[:10]
print(first_10_rows)
Output:
City Temperature (F) Humidity (%)
0 Phoenix 65 67
1 Houston 98 78
2 Chicago 71 76
3 Chicago 45 79
4 Houston 84 63
5 Chicago 71 69
6 Phoenix 76 47
7 Chicago 49 66
8 Phoenix 90 67
9 Los Angeles 84 70
Post-execution of the code in Pycharm, the output is captured in the screenshot presented below.
4. Pandas show first 10 rows through looping
Looping through the dataframe using iterrows() in Python, provides row-by-row iteration. This method is useful for complex conditions or operations within the first 10 rows.
This way we can print first 10 rows from a Pandas dataframe in Python:
import pandas as pd
import numpy as np
states = ['New York', 'California', 'Texas', 'Florida', 'Illinois']
covid_data = {
'State': np.random.choice(states, 50),
'Cases': np.random.randint(1000, 500000, size=50),
'Deaths': np.random.randint(50, 20000, size=50)
}
covid_df = pd.DataFrame(covid_data)
for index, row in covid_df.iterrows():
print(row)
if index == 9:
break
Output:
State Texas
Cases 348362
Deaths 18429
Name: 0, dtype: object
State Texas
Cases 343215
Deaths 11058
Name: 1, dtype: object
State Florida
Cases 438503
Deaths 18001
Name: 2, dtype: object
State California
Cases 207090
Deaths 12869
Name: 3, dtype: object
State California
Cases 132583
Deaths 4722
Name: 4, dtype: object
State New York
Cases 4846
Deaths 5746
Name: 5, dtype: object
State New York
Cases 119603
Deaths 7144
Name: 6, dtype: object
State Texas
Cases 357957
Deaths 7637
Name: 7, dtype: object
State New York
Cases 68380
Deaths 15801
Name: 8, dtype: object
State California
Cases 236428
Deaths 18211
Name: 9, dtype: object
The screenshot below illustrates the output after the code was implemented in the Pycharm editor.
5. Print the first 10 rows of a Pandas dataframe using the query() method
The query() method allows for querying the DataFrame based on a condition in Python. For example, df.query(“index < 10”) will return rows where the index is less than 10.
Here is the use of the query() method to print first 10 rows from a Pandas dataframe in Python
import pandas as pd
data = {'City': ['New York City', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Philadelphia', 'San Antonio', 'San Diego', 'Dallas', 'San Jose'],
'Population (millions)': [8.40, 3.97, 2.70, 2.32, 1.70, 1.58, 1.53, 1.42, 1.34, 1.03]}
df = pd.DataFrame(data)
first_10_rows = df.query('index < 10')
print(first_10_rows)
Output:
City Population (millions)
0 New York City 8.40
1 Los Angeles 3.97
2 Chicago 2.70
3 Houston 2.32
4 Phoenix 1.70
5 Philadelphia 1.58
6 San Antonio 1.53
7 San Diego 1.42
8 Dallas 1.34
9 San Jose 1.03
Following the execution of the code in the Pycharm editor, the screenshot provided below displays the output.
6. Pandas get first row using the tail() method with negative indexing
We can use the tail() method with negative indexing, like df.tail(-len(df) + 10), which is an unconventional way to display the first 10 rows by excluding all but the last 10 rows in Python.
This way we can use the tail() function to print first 10 rows from a Pandas dataframe in Python:
import pandas as pd
import numpy as np
cities = ['New York City', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix']
crime_data = {
'City': np.random.choice(cities, 50),
'Crime_Rate (per 1000)': np.random.randint(100, 1000, size=50)
}
crime_df = pd.DataFrame(crime_data)
first_10_rows = crime_df.query('index < 10')
print(first_10_rows)
Output:
City Crime_Rate (per 1000)
0 Houston 334
1 Chicago 876
2 Phoenix 492
3 Houston 735
4 Phoenix 891
5 Phoenix 188
6 New York City 412
7 Houston 757
8 New York City 502
9 Houston 189
After the execution of the code in the Pycharm editor, the screenshot below captures the resulting output.
Conclusion
Understanding how to print first 10 rows from a Pandas dataframe in Python is essential for efficient data analysis. Methods like the head() method, index slicing, the iloc method, looping through rows with iterrows(), the query() method, and using the tail() method with negative indexing offer diverse approaches to achieve this.
Each technique caters to different scenarios and preferences, ensuring that we can always access and inspect our data quickly and effectively.
You may also like to read:
- How to Filter DataFrame in Python Pandas
- Pandas count rows with condition in Python
- Pandas find index of value in Python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.