gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:44:59 28 4
gpt4 key购买 nike

如何合并重复的 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

谢谢!

最佳答案

# 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

关于python - Pandas 合并重复的 DataFrame 列,保留列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41324173/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com