如何在Pandas中实现指定的DataFrame转换?
Pandas实现DataFrame结构转换方案
需求说明
将包含学生姓名、储蓄、支出的输入DataFrame,转换为以学生A为固定Student1,与其余所有学生配对,并分别提取双方支出(Student1E/Student2E)和储蓄(Student1S/Student2S)的目标结构。
输入DataFrame
| Name Std | Savings | Expense |
|---|---|---|
| A | 100000 | 500000 |
| B | 200000 | 600000 |
| C | 300000 | 700000 |
| D | 400000 | 800000 |
实现代码
import pandas as pd # 1. 构建输入DataFrame df_input = pd.DataFrame({ 'Name Std': ['A', 'B', 'C', 'D'], 'Savings': [100000, 200000, 300000, 400000], 'Expense': [500000, 600000, 700000, 800000] }) # 2. 拆分并重命名数据 # 提取固定为Student1的A的信息 student1 = df_input[df_input['Name Std'] == 'A'].rename(columns={ 'Name Std': 'Student1', 'Expense': 'Student1E', 'Savings': 'Student1S' }) # 提取其余学生作为Student2的信息 student2 = df_input[df_input['Name Std'] != 'A'].rename(columns={ 'Name Std': 'Student2', 'Expense': 'Student2E', 'Savings': 'Student2S' }) # 3. 交叉连接生成目标DataFrame(Pandas 1.2.0+支持) df_output = student1.merge(student2, how='cross')[['Student1', 'Student2', 'Student1E', 'Student2E', 'Student1S', 'Student2S']] # 兼容Pandas旧版本的写法(低于1.2.0) # student1['key'] = 1 # student2['key'] = 1 # df_output = student1.merge(student2, on='key').drop('key', axis=1)[['Student1', 'Student2', 'Student1E', 'Student2E', 'Student1S', 'Student2S']] # 查看结果 print(df_output)
输出结果
| Student1 | Student2 | Student1E | Student2E | Student1S | Student2S |
|---|---|---|---|---|---|
| A | B | 500000 | 600000 | 100000 | 200000 |
| A | C | 500000 | 700000 | 100000 | 300000 |
| A | D | 500000 | 800000 | 100000 | 400000 |
代码说明
- 通过筛选和重命名,分别生成
Student1(固定为A)和Student2(其余学生)的数据集; - 使用交叉连接(
merge(how='cross'))实现两个数据集的全配对,得到A与其他所有学生的组合; - 最后调整列顺序,完全匹配目标结构。
内容的提问来源于stack exchange,提问作者Shounak Sushanta Dasgupta
相关产品推荐
相关产品推荐

