w3resource

Selecting rows by position in Pandas DataFrame


9. Select First Three Rows Using iloc

Write a Pandas program to select the first three rows using iloc.

Sample Solution :

Python Code :

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
    'X': [1, 6, 8, 3, 7],
    'Y': [5, 2, 9, 4, 1]
})

# Select first three rows using iloc
result = df.iloc[:4]
print(result)

Output:

   X  Y
0  1  5
1  6  2
2  8  9
3  3  4

Explanation:

  • Import pandas library.
  • Create a DataFrame.
  • Use .iloc to select the first three rows.
  • Print the results.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to select and display the first three rows of a DataFrame using iloc indexing.
  • Write a Pandas program to use iloc to extract the first three rows and then reset the DataFrame index.
  • Write a Pandas program to slice the first three rows of a DataFrame with iloc and then compute the sum of a specific column.
  • Write a Pandas program to select the top three rows using iloc and then convert the result into a new DataFrame.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Boolean indexing in Pandas DataFrame.
Next: Conditional selection with .loc in Pandas DataFrame.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.