首页 > 解决方案 > 同一数据框中的列映射

问题描述

Students  Score1  Students  Score2  Students  Score3
   A        50       B        88       A        48
   B        40       A        76       C        47
   C        28       C        74       B        40

如何将上述数据框转换为以下格式:

Students  Score1  Score2  Score3
   A        50      76      48
   B        40      88      40
   C        28      74      47

我知道的唯一方法是将 iloc 应用到单独的数据框中,然后将它们连接在一起,还是有一种方法可以这样做?*Python 将重复的列读取为 Student、Students.1、Students.2 等。

标签: pythonpandasdataframe

解决方案


concat和_groupby

pd.concat([
    d.set_index('Students')
    for _, d in df.groupby(np.arange(df.shape[1]) // 2, axis=1)
], axis=1)

   Score1  Score2  Score3
A      50      76      48
B      40      88      40
C      28      74      47

pd.concat([
    d.set_index('Students')
    for _, d in df.groupby(np.arange(df.shape[1]) // 2, axis=1)
], axis=1).rename_axis('Students').reset_index()

  Students  Score1  Score2  Score3
0        A      50      76      48
1        B      40      88      40
2        C      28      74      47

推荐阅读