Remove pandas DataFrame Column by Index in Python (2 Examples)

In this Python tutorial you’ll learn how to remove a pandas DataFrame variable by index.

Example Data

import pandas as pd                                             # Import pandas
my_df = pd.DataFrame({'A':range(5, 12),                         # Constructing pandas DataFrame
                      'B':range(22, 15, - 1),
                      'C':range(9, 16),
                      'D':range(19, 26)})
print(my_df)
#     A   B   C   D
# 0   5  22   9  19
# 1   6  21  10  20
# 2   7  20  11  21
# 3   8  19  12  22
# 4   9  18  13  23
# 5  10  17  14  24
# 6  11  16  15  25

Example 1: Delete Single Column from pandas DataFrame by Index

df_drop_one = my_df.drop(my_df.columns[3], axis = 1)            # Removing one variable
print(df_drop_one)
#     A   B   C
# 0   5  22   9
# 1   6  21  10
# 2   7  20  11
# 3   8  19  12
# 4   9  18  13
# 5  10  17  14
# 6  11  16  15

Example 2: Delete Multiple Columns from pandas DataFrame by Index

df_drop_multiple = my_df.drop(my_df.columns[[1, 3]], axis = 1)  # Removing multiple variables
print(df_drop_multiple)
#     A   C
# 0   5   9
# 1   6  10
# 2   7  11
# 3   8  12
# 4   9  13
# 5  10  14
# 6  11  15

Related Tutorials

You may have a look at the following Python programming tutorials. They explain topics such as data conversion and lists.

Leave a Reply

Your email address will not be published.

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