给定一个数据框,我想找到所有重复的列(列名不同,值相同),然后按键将它们分组到字典中。我有一个解决方案,但它涉及一个嵌套的 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']}
添加回答
举报
0/150
提交
取消