python - 同一数据框中的列映射
问题描述
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 等。
解决方案
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
推荐阅读
- node.js - 如何从 bot 内部向 Microsoft bot 发送消息,以便消息通过对话流并获得相应的响应?
- sql - SQL Server 递归笛卡尔
- r - 使用 IF、THEN 和随机值创建创建新变量
- django - 如何在 django 中使用像 AJAX 调用这样的视图?
- javascript - 强制使用 VideoJS 在 HLS 中使用质量级别
- c++ - 支持 const 和非 const 实例的类的 C++ const 正确性/缺少 const 构造函数
- java - 是否可以删除 Java 中的 keyTyped 和 keyReleased 方法?
- reactjs - 如何将选取的 dateValue(使用 react-day-picker)导入到另一个位于同一层次结构级别 ReactJS 的文件中?
- laravel - Laravel 和 Vue.js 循环函数
- julia - 在 macOSX 上的 julia 中安装 SymEngine