logo
  • Home
  • Contact
💵
Should I be buying I-Bonds in 2023?
💰
Need a step-by-step guide to opening your Roth IRA?
Buy me a coffee Buy me a coffee
aws c++ career cli css docker finance git java js misc python sql

How to Select the First n Rows of a Pandas DataFrame


How can we select the first n rows of a Pandas DataFrame?

Suppose we’re working with this DataFrame df.

     x1   x2  x3  x4  y
0     7  143  22  23  1
1     1   23  22  29  0
2     3  133  24   0  1
3     1   39  27  23  0
4     0  137  40  23  1

If we only want the first 2 rows, then we can either slice by the actual index, or use -1.

df.iloc[:2,:]
df.iloc[:-1,:]

If we only want the last row (index of 4), once again, we can either slice by the actual index, or use -1.

df.iloc[4:,:]
df.iloc[-1:,:]

Related in Python

How to Append to a File or Create If Not Exists in Python
How to Sleep in Python (adding delays)
How to Run `conda activate` in a Shell Script
How to Set Axis Range in Matplotlib (Python)
How to Calculate Mean Across the Row or Column in a NumPy Array
How to Install Playwright with Conda in Python
How to Get Rows or Columns with NaN (null) Values in a Pandas DataFrame
How to Create a Pandas DataFrame
How to Delete a Row Based on a Column Value in a Pandas DataFrame
How to Get the Maximum Value in a Column of a Pandas DataFrame
How to Keep Certain Columns in a Pandas DataFrame
How to Count Number of Rows or Columns in a Pandas DataFrame
How to Add List to Set in Python
How to Fix "Assertion !bs->started failed" in PyBGPStream
How to Add a Row to a Pandas DataFrame
How to Remove Duplicate Columns on Join in a Spark DataFrame
© , LogFetch   âˆ™   Advertise Here   âˆ™   Privacy Policy