Remove Variable from pandas DataFrame in Python (2 Examples)

In this post you’ll learn how to drop one or multiple variables from a pandas DataFrame in the Python programming language.

Preparing the Examples

import pandas as pd                                # Import pandas library in Python
my_df = pd.DataFrame({"col1":range(1, 6),         # Constructing pandas DataFrame in Python
                      "col2":["a", "f", "f", "h", "i"],
                      "col3":[5, 8, 7, 3, 1],
                      "col4":range(5, 0, - 1),
                      "col5":range(50, 55)})
print(my_df)                                      # Displaying pandas DataFrame
#    col1 col2  col3  col4  col5
# 0     1    a     5     5    50
# 1     2    f     8     4    51
# 2     3    f     7     3    52
# 3     4    h     3     2    53
# 4     5    i     1     1    54

Example 1: Deleting Column from pandas DataFrame According to Name

my_df_a = my_df.drop("col5", axis = 1)            # Remove col5
print(my_df_a)                                    # Displaying new DataFrame
#    col1 col2  col3  col4
# 0     1    a     5     5
# 1     2    f     8     4
# 2     3    f     7     3
# 3     4    h     3     2
# 4     5    i     1     1

Example 2: Deleting Several Columns from pandas DataFrame According to Name

my_df_b = my_df.drop(["col2", "col4"], axis = 1)  # Remove col2 & col4
print(my_df_b)                                    # Displaying new DataFrame
#    col1  col3  col5
# 0     1     5    50
# 1     2     8    51
# 2     3     7    52
# 3     4     3    53
# 4     5     1    54

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