Pandas DataFrame truncate() Method


Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

  • The Pandas library enables access to/from a DataFrame.
  • The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required libraries.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd
import numpy as np 

DataFrame truncate()

The truncate() method truncates a DataFrame/Series before and after a selected index value.

The syntax for this method is as follows:

DataFrame.truncate(before=None, after=None, axis=None, copy=True)
ParameterDescription
beforeTruncate (remove) rows before a said index value. The data type can be a date, string, or integer.  
afterTruncate (remove) rows after a said index value. The data type can be a date, string, or integer.
axisIf zero (0) or index is selected, apply to each column. Default 0.
If one (1) apply to each row.
copyIf True, a copy of the truncated DataFrame/Series returns. This boolean is True by default.

For this example, we have a DataFrame containing a message.

df = pd.DataFrame({'C': ['f', 'i', 'n', 'x', 't', 'e', 'r'],
                   'O': ['p', 'u', 'z', 'z', 'l', 'e', 's'],
                   'D': ['a', 'w', 'e', 's', 'o', 'm', 'e'],
                   'E': ['w', 'a', 'y', '-', 't', 'o', '-'],
                   'R': ['l', 'e', 'r', 'n', '!', '!', '!']},
                   index=[1, 2, 3, 4, 5, 6, 7])
print(df)

result = df.truncate(before=2, after=4)                  
print(result)
  • Line [1] creates a DataFrame from a dictionary of lists and saves it to df.
  • Line [2] outputs the result to the terminal.
  • Line [3] truncates and saves the output to the result variable.
  • Line [4] outputs the result to the terminal.

Output

df
result

More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.