首页 > 解决方案 > 仅当值不同时才创建新列

问题描述

我的数据框如下所示:

pd.DataFrame([["t1","d2","e3","r4"],
         ["t1","d2","e2","r4"],
         ["t1","d2","e1","r4"]],columns=["a","b","c","d"])

而且我要:

pd.DataFrame([["t1","d2","e3","r4","e1","e2"]],
columns=["a","b","c","d","c1","c2"])

即我只有一列值不同,我想创建一个新的数据框,并在观察到新值时添加列。是否有捷径可寻 ?

标签: pythonpandasdataframe

解决方案


编辑:概括任何单个非唯一列:

Ucols = df.columns[(df.nunique() == 1)].tolist()
df_out = df.set_index(Ucols).set_index(df.groupby(Ucols).cumcount(), append=True).unstack()
df_out.columns = [f'{i}{j}' if j != 0 else f'{i}' for i,j in df_out.columns]
print(df_out.reset_index())

输出:

    a   b   d   c  c1  c2
0  t1  d2  r4  e3  e2  e1

原始答案

利用:

df_out = df.set_index(['a','b','d',df.groupby(['a','b','d']).cumcount()]).unstack()

df_out.columns = [f'{i}{j}' if j != 0 else f'{i}' for i,j in df_out.columns]

df_out.reset_index()

输出:

    a   b   d   c  c1  c2
0  t1  d2  r4  e3  e2  e1

推荐阅读