为了账号安全,请及时绑定邮箱和手机立即绑定

在 Pandas 数据框中查找所有重复的列,然后按键对它们进行分组

在 Pandas 数据框中查找所有重复的列,然后按键对它们进行分组

撒科打诨 2021-11-02 15:06:14
给定一个数据框,我想找到所有重复的列(列名不同,值相同),然后按键将它们分组到字典中。我有一个解决方案,但它涉及一个嵌套的 for 循环,我认为应该有一种方法可以更优雅或更直接地在 Pandas 中执行此操作。我正在使用删除重复列...作为我当前解决方案的一部分。这在列表中找到重复项...听起来与我的问题相似,但回答了不同的问题。我的原始应用程序是为缺失数据创建掩码列,并能够为具有相同缺失数据模式的所有列使用单个掩码列。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': []}
查看完整描述

1 回答

?
慕仙森

TA贡献1827条经验 获得超8个赞

您可以使用除第一列之外的所有列进行分组(因为它对应于原始列名),然后使用字典理解和扩展的可迭代解包构建预期结果:


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']}


查看完整回答
反对 回复 2021-11-02
  • 1 回答
  • 0 关注
  • 201 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号