熊猫。检查列名是否唯一

问题描述 投票:0回答:2

我正在使用

read_excel()
方法将一些数据导入 pandas DataFrame。问题是,我的 .xlsx 文件可能有一些名称相同的列(例如“gamma”和“gamma”)。我不会处理这些数据,我会在这里抛出一个异常。但我不知道如何检查列是否唯一。导入后,pandas 通过在末尾添加 .digit 重命名具有相同名称的列,我不能这样做 (
len(list(df.columns)) == len(set(df.columns))
)。

注意: 我会遇到实际列名以.digit结尾的情况,所以这个解决方案会引入一些错误,所以我做不到

if any(".1" in col for col in df.columns): raise Exception(...)

    alpha   beta    gamma   gamma.1
0   1   9   1   35
1   2   8   543 12
2   3   7   6   45
3   4   6   4   64
4   5   5   2   865
5   6   4   56  235
6   7   3   6   124
7   8   2   2   135
8   9   1   26  767

如何检查列名是否重复?谢谢。

python pandas dataframe
2个回答
1
投票

如果你只是想检查你可以做这样的事情:

test_excel = pd.read_excel("data/test.xlsx", nrows=0).keys().tolist()
for i in test_excel:
    if '.' in i:
        print("There's a duplicate")

不是最雄辩的,但它会是你所要求的。您可以根据需要修改功能

可能值得关注 pandas 的未来更新。如果您阅读文档,它会说明以下内容:

mangle_dupe_cols: bool, default True

Duplicate columns will be specified as ‘X’, ‘X.1’, …’X.N’, rather than ‘X’…’X’. Passing in False will cause data to be overwritten if there are duplicate names in the columns.

Deprecated since version 1.5.0: Not implemented, and a new argument to 为将添加的重复列的名称指定模式 相反

所以将来你将能够编写更简单的代码来处理它。


1
投票

只读取您的标题作为正常数据并检查重复项:

import pandas as pd

df = pd.read_excel("file.xlsx", header=None, nrows=1)
if not df.iloc[0].is_unique:
    raise Exception("Duplicates")

这需要您打开文件两次。虽然,第一次您只从中读取一行。如果你仍然想避免它,你可以这样做:

df = pd.read_excel("file.xlsx", header=None)

columns = df.iloc[0]
if not columns.is_unique:
    raise Exception("Duplicates")

df.drop(0, inplace=True)
df.columns = columns
© www.soinside.com 2019 - 2024. All rights reserved.