首页 > 解决方案 > 如何将熊猫数据框中的所有行与特定列的相同值合并?

问题描述

我有一个数据框,例如:

person_ID, first_name, last_name, feature_1, feature_2, feature_3
1, John, Talbert, 1,2,3
2, Ted, Thompson, 4,5,6
1, John, Talbert, 7,8,9
2, Ted, Thompson, 13,14,15

我想重新格式化它:

person_ID, first_name, last_name, feature_1_A, feature_2_A, feature_3_A, feature_1_B, feature_2_B, feature_3_B, 
1, John, Talbert, 1,2,3, 7,8,9
2, Ted, Thompson, 4,5,6,13,14,15

知道什么是有效的方法吗?数据集很小,因此它实际上不必非常高效。

预先感谢您的帮助。

标签: pythonpandasdataframepandas-groupby

解决方案


这本质上是枢轴和重命名:

df['col'] = df.groupby('person_ID').cumcount()

out=df.pivot_table(index=['person_ID','first_name','last_name'], 
                   columns='col', aggfunc='first')
out.columns = [f'{x}_{y}' for x,y in out.columns]
out = out.reset_index()

输出:

   person_ID first_name last_name  feature_1_0  feature_1_1  feature_2_0  feature_2_1  feature_3_0  feature_3_1
0          1       John   Talbert            1            7            2            8            3            9
1          2        Ted  Thompson            4           13            5           14            6           15

推荐阅读