首页 > 解决方案 > 从列表中查找重复的 csv 列 [python pandas]

问题描述

我想从列表中找到重复的列,而不是任何列。

正确的 csv 示例如下所示:

col1, col2, col3, col4, custom, custom
1,2,3,4,test,test
4,3,2,1,test,test

列表如下所示:

columnNames = ['col1', 'col2', 'col3', 'col4']

因此,当我运行类似df.columns.duplicated()我不想检测重复的“自定义”字段时,只有当有多个“col1”列或多个“col2”列等时,才返回 True这些列被发现是重复的。

我发现在示例中包含重复的“colN”列名 col4 时,我将其打印出来,它告诉我index(['col1', 'col2', 'col3', 'col4', 'col4.1'], dtype='object')

不知道如何编写那行代码。

标签: pythonpython-3.xpandasdataframecsv

解决方案


使用Index.isin+Index.duplicated创建一个布尔掩码:

c = df.columns.str.rsplit('.', n=1).str[0]
mask = c.isin(columnNames) & c.duplicated()

如果要查找重复的列名,请boolean indexing使用mask

dupe_cols = df.columns[mask]

推荐阅读