深度阅读

how to drop a duplicate column in pandas ?

作者
作者
2023年08月22日
更新时间
6.96 分钟
阅读时间
0
阅读量

To drop a duplicate column in pandas, you can use the duplicated() and drop() methods. Here’s an example of how to do this:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3],
                   'B': [4, 5, 6],
                   'C': [4, 5, 6]})

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

print(df)

In this example, we’re checking if there are any duplicated column names in the DataFrame using duplicated(). If there are duplicates, we’re using boolean indexing (~) to drop them using df.loc[:, ~df.columns.duplicated()].

This will remove all duplicate columns in the DataFrame while keeping the original order of the columns.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。