繁体   English   中英

如何删除具有重复值的不同列名?

[英]How to delete different column names with duplicated values?

给定这个 DF:

a   b   c   d
1   2   1   4
4   3   4   2
foo bar foo yes

在大型 pandas DF 中删除相同但名称不同的列的最佳方法是什么? 例如:

a   b   d
1   2   4
4   3   2
foo bar yes

列 c 已从上述 dataframe 中删除,因为 a 和 c 列相同但名称不同。 到目前为止,我试图

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

但是我不清楚如何检查 DF 中的行值?

如下使用transpose

df.T.drop_duplicates().T

我尝试了直接的方法 - 遍历列名并将每一列与其他列的 rest 进行比较。 使用np.all进行完全匹配。 这些方法只用了 336ms。

repeated_columns = []
for i, column in enumerate(df.columns):
    r_columns = df.columns[i+1:]
    for r_c in r_columns:
        if np.all(df[column] == df[r_c]):
            repeated_columns.append(r_c)
new_columns = [x for x in df.columns if x not in repeated_columns]
df[new_columns]

它会给你以下 output

     a    b    d
0    1    2    4
1    4    3    2
2  foo  bar  yes
df.loc[:,~df.T.duplicated()]
     a    b    d
0    1    2    4
1    4    3    2
2  foo  bar  yes

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM