Categories
Python Answers

How to remove duplicate columns with Python Pandas?

Spread the love

Sometimes, we want to remove duplicate columns with Python Pandas.

In this article, we’ll look at how to remove duplicate columns with Python Pandas.

How to remove duplicate columns with Python Pandas?

To remove duplicate columns with Python Pandas, we can use ~ with the df.columns.duplicated method.

For instance, we write

df = df.loc[:,~df.columns.duplicated()]

to remove columns based on duplicate column names by slicing the data frame with

df.loc[:,~df.columns.duplicated()]

We use it to return all the columns that have unique column names and assign the returned data frame back to df.

Conclusion

To remove duplicate columns with Python Pandas, we can use ~ with the df.columns.duplicated method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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