Pandas合并重复的DataFrame列,保留列名

时间:2016-12-25 20:08:16

标签: python pandas dataframe duplicates data-science

如何合并重复的DataFrame列并保留所有原始列名?

e.g。如果我有DataFrame

df = pd.DataFrame({"col1" : [0, 0, 1, 2, 5, 3, 7],
                   "col2" : [0, 1, 2, 3, 3, 3, 4],
                   "col3" : [0, 1, 2, 3, 3, 3, 4]})

我可以使用

删除重复的列(是的,转置对于大型DataFrame来说很慢)
df.T.drop_duplicates().T

但这只保留每个唯一列的一个列名

    col1 col2
 0   0   0
 1   0   1
 2   1   2
 3   2   3
 4   5   3
 5   3   3
 6   7   4

如何保留合并哪些列的信息?例如

之类的东西
    [col1] [col2, col3]
 0     0         0
 1     0         1
 2     1         2
 3     2         3
 4     5         3
 5     3         3
 6     7         4

谢谢!

2 个答案:

答案 0 :(得分:2)

# group columns by their values 
grouped_columns = df.groupby(list(df.values), axis=1).apply(lambda g: g.columns.tolist())  

# pick one column from each group of the columns
unique_df = df.loc[:, grouped_columns.str[0]]

# make a new column name for each group, don't think the list can work as a column name, you need to join them
unique_df.columns = grouped_columns.apply("-".join)

unique_df

enter image description here

答案 1 :(得分:1)

我还使用了Ttuplegroupby

def f(x):
    d = x.iloc[[0]]
    d.index = ['-'.join(x.index.tolist())]
    return d

df.T.groupby(df.apply(tuple), group_keys=False).apply(f).T

enter image description here