【问题标题】:Find all duplicate columns in a pandas dataframe and then group them by key在 pandas 数据框中查找所有重复的列,然后按键分组
【发布时间】:2019-02-08 09:16:20
【问题描述】:

给定一个数据框,我想找到所有重复的列(列名不同,值相同),然后将它们按键分组到字典中。我有一个解决方案,但它涉及一个嵌套的 for 循环,我认为应该有一种方法可以更优雅地或更直接地在 pandas 中执行此操作。我正在使用remove duplicate columns... 作为我当前解决方案的一部分。这个find duplicates in list... 听起来与我的问题相似,但回答了一个不同的问题。我最初的应用程序是为丢失的数据创建掩码列,并能够对具有相同缺失数据模式的所有列使用单个掩码列。

df = pd.DataFrame({'col1':[0,1,2,3,4],'col2':[1,0,0,0,1],'col3':[1,0,0,0,1],'col4':[1,0,1,0,1],'col5':[1,0,1,0,1],'col6':[1,1,1,0,1],'col7':[1,0,0,0,1] })
dup_cols = df.T.drop_duplicates().T.columns.tolist()
tmp_dict = {}
for col in dup_cols:
    tmp[col] = []
for col in dup_cols:
    check_cols = [c for c in df.columns if c != col]
    for c in check_cols:
        if np.array_equal(df[col].values,df[c].values):
            tmp_dict[col].append(c)

>>>tmp_dict
{'col1': [], 'col2': ['col3', 'col7'], 'col4': ['col5'], 'col6': []}

【问题讨论】:

  • 如果您还没有这样做,我建议您查看 df.fillna() 以替换 NaN。您可以为每列指定单独的填充值,因此可能不需要创建掩码。
  • @WolfgangK 我看不出这对 OP 的问题有何帮助...
  • 我不太了解你的最终目标,但我认为你可以通过定义 df1 = df.T 来简化一切,然后你可以做 df1.drop_duplicates() 并最后转回。

标签: python pandas


【解决方案1】:

您可以使用除第一列之外的所有列进行分组(因为它对应于原始列名),然后使用 dictionary comprehensionextended iterable unpacking 构建预期结果:

import pandas as pd

df = pd.DataFrame({'col1': [0, 1, 2, 3, 4], 'col2': [1, 0, 0, 0, 1], 'col3': [1, 0, 0, 0, 1], 'col4': [1, 0, 1, 0, 1],
                   'col5': [1, 0, 1, 0, 1], 'col6': [1, 1, 1, 0, 1], 'col7': [1, 0, 0, 0, 1]})

transpose = df.T

# build all column list but the first
columns = list(range(1, len(df)))

# build result iterating over groups
result = {head: tail for _, (head, *tail) in transpose.reset_index().groupby(columns).index}

print(result)

输出

{'col1': [], 'col4': ['col5'], 'col6': [], 'col2': ['col3', 'col7']}

【讨论】:

  • 您能否添加更多关于字典理解如何与扩展的可迭代解包一起工作的细节?试图把我的头缠住。我看到需要*tail,但对for _, (head, *tail) 感到困惑
  • @ZakKeirn ... groupby(columns).index 返回一个键值元组,在您的情况下,您只关心值,因此键的 _ 表示您不关心该元素。
  • 我理解这个解决方案的关键是打印出 'list(transpose.reset_index().groupby(columns).index)` 并记下结构。
猜你喜欢
  • 1970-01-01
  • 2020-10-08
  • 2020-11-11
  • 2018-03-20
  • 2015-04-30
  • 2013-07-10
  • 2019-03-20
  • 2016-06-05
  • 2022-08-21
相关资源
最近更新 更多