Pandas: Get first n records of a DataFrame
59. Get First n Records
Write a Pandas program to get first n records of a DataFrame.
Sample Solution :
Python Code :
import pandas as pd
d = {'col1': [1, 2, 3, 4, 7, 11], 'col2': [4, 5, 6, 9, 5, 0], 'col3': [7, 5, 8, 12, 1,11]}
df = pd.DataFrame(data=d)
print("Original DataFrame")
print(df)
print("\nFirst 3 rows of the said DataFrame':")
df1 = df.head(3)
print(df1)
Sample Output:
Original DataFrame col1 col2 col3 0 1 4 7 1 2 5 5 2 3 6 8 3 4 9 12 4 7 5 1 5 11 0 11 First 3 rows of the said DataFrame': col1 col2 col3 0 1 4 7 1 2 5 5 2 3 6 8
For more Practice: Solve these Related Problems:
- Write a Pandas program to display the first n rows of a DataFrame using the head() method and then reset the index.
- Write a Pandas program to extract the first n records and then calculate the average of a numeric column within these records.
- Write a Pandas program to get the top n rows of a DataFrame and then export this subset to a CSV file.
- Write a Pandas program to select the first n records, then apply a filter to display only those rows where a specific column exceeds a threshold.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Pandas program to get first n records of a DataFrame.
Next: Write a Pandas program to get last n records of a DataFrame.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.