Delete First & Last N Columns from pandas DataFrame in Python (2 Examples)

In this tutorial you’ll learn how to remove the first and last N variables from a pandas DataFrame in Python programming.

Setting up the Examples

import pandas as pd                       # Import pandas library in Python
my_df = pd.DataFrame({'A':range(1, 5),    # Construct pandas DataFrame
                      'B':range(5, 1, - 1),
                      'C':range(10, 14),
                      'D':range(20, 24),
                      'E':range(0, 4),
                      'F':range(17, 13, - 1)})
print(my_df)
#    A  B   C   D  E   F
# 0  1  5  10  20  0  17
# 1  2  4  11  21  1  16
# 2  3  3  12  22  2  15
# 3  4  2  13  23  3  14

Example 1: Removing the First N Variables from a pandas DataFrame

my_df_last = my_df.iloc[:, 2:]            # Returning last columns
print(my_df_last)
#     C   D  E   F
# 0  10  20  0  17
# 1  11  21  1  16
# 2  12  22  2  15
# 3  13  23  3  14

Example 2: Removing the Last N Variables from a pandas DataFrame

my_df_first = my_df.iloc[:, :4]           # Returning first columns
print(my_df_first)
#    A  B   C   D
# 0  1  5  10  20
# 1  2  4  11  21
# 2  3  3  12  22
# 3  4  2  13  23

Related Articles & Further Resources

Have a look at the following Python tutorials. They focus on similar topics as this post:

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top