How to get the last N rows of a pandas DataFrame?

How to get the last N rows of a pandas DataFrame?

To get the last N rows of a Pandas DataFrame, you can use the .tail(N) method, where N is the number of rows you want to retrieve from the end of the DataFrame. Here's how to do it:

import pandas as pd # Sample DataFrame data = {'A': [1, 2, 3, 4, 5], 'B': ['apple', 'banana', 'cherry', 'date', 'elderberry']} df = pd.DataFrame(data) # Get the last 3 rows last_N_rows = df.tail(3) print(last_N_rows) 

Output:

 A B 2 3 cherry 3 4 date 4 5 elderberry 

In this example, we used the .tail(3) method to retrieve the last 3 rows of the DataFrame. You can replace 3 with any integer value to get the desired number of last rows.

The .tail(N) method returns a new DataFrame containing the last N rows of the original DataFrame, preserving the index and column structure.

Examples

  1. "Pandas get last N rows" Description: Retrieve the last N rows of a pandas DataFrame using the tail() method.

    last_n_rows = df.tail(N) 
  2. "Pandas access last N rows of DataFrame" Description: Access the last N rows of a pandas DataFrame using slicing.

    last_n_rows = df[-N:] 
  3. "Pandas get last N rows from DataFrame" Description: Get the last N rows of a pandas DataFrame using the iloc method.

    last_n_rows = df.iloc[-N:] 
  4. "Pandas extract last N rows DataFrame" Description: Extract the last N rows of a pandas DataFrame using the tail() method.

    last_n_rows = df.tail(N) 
  5. "Pandas retrieve last N rows DataFrame" Description: Retrieve the last N rows of a pandas DataFrame using the iloc method.

    last_n_rows = df.iloc[-N:] 
  6. "Pandas access last N rows" Description: Access the last N rows of a pandas DataFrame using the tail() method.

    last_n_rows = df.tail(N) 
  7. "Pandas get last N rows with slicing" Description: Get the last N rows of a pandas DataFrame using slicing.

    last_n_rows = df[-N:] 
  8. "Pandas extract last N rows with iloc" Description: Extract the last N rows of a pandas DataFrame using the iloc method.

    last_n_rows = df.iloc[-N:] 
  9. "Pandas retrieve last N rows using tail" Description: Retrieve the last N rows of a pandas DataFrame using the tail() method.

    last_n_rows = df.tail(N) 
  10. "Pandas access last N rows with iloc" Description: Access the last N rows of a pandas DataFrame using the iloc method.

    last_n_rows = df.iloc[-N:] 

More Tags

xpath propertygrid haml angular-google-maps icons class-method stepper minecraft geolocation nsregularexpression

More Python Questions

More Biology Calculators

More Statistics Calculators

More Weather Calculators

More Cat Calculators