Get last n records of a Pandas DataFrame

Get last n records of a Pandas DataFrame

If you want to retrieve the last n records of a Pandas DataFrame, you can use the tail() method.

Here's how you can do it:

  • Firstly, import the necessary libraries:
import pandas as pd 
  • Create a sample DataFrame:
data = { 'A': range(1, 11), 'B': range(11, 21) } df = pd.DataFrame(data) print(df) 

This will create a DataFrame with 10 rows.

  • Get the last n records:

To get the last n records, use the tail(n) method on the DataFrame:

n = 3 last_n_records = df.tail(n) print(last_n_records) 

For the above example, this will print:

 A B 7 8 18 8 9 19 9 10 20 

The tail() method, when called without any arguments, will return the last 5 rows by default. Adjust the value of n to retrieve the desired number of records.


More Tags

angular-fullstack bufferedreader cx-oracle race-condition fork iformfile highest vuforia google-sheets-formula web-audio-api

More Programming Guides

Other Guides

More Programming Examples