如何在Pandas中重新定位表格元素并调整布局
Pandas 表格结构重排解决方案
原始表格
| Type Label | Initial | 2022 | 2023 | Difference |
|---|---|---|---|---|
| APPS | A/B/C | 500 | 469 | 31 |
| BACS | B/C/D | 5 | 3 | 2 |
| CAPS | C/D/E | 10 | 5 | 5 |
目标表格
| Type Label/Initial | 2022 | 2023 | Difference |
|---|---|---|---|
| APPS | 500 | 469 | 31 |
| A | |||
| B | |||
| C | |||
| BACS | 5 | 3 | 2 |
| B | |||
| C | |||
| D | |||
| CAPS | 10 | 5 | 5 |
| C | |||
| D | |||
| E |
实现代码
import pandas as pd # 读取或构造原始数据(这里直接构造示例数据) df = pd.DataFrame({ 'Type Label': ['APPS', 'BACS', 'CAPS'], 'Initial': ['A/B/C', 'B/C/D', 'C/D/E'], '2022': [500, 5, 10], '2023': [469, 3, 5], 'Difference': [31, 2, 5] }) # 初始化存储结果的列表 result_rows = [] # 遍历原始表格每一行,拆分重组内容 for _, row in df.iterrows(): # 添加带加粗格式的Type Label行 result_rows.append({ 'Type Label/Initial': f"**{row['Type Label']}**", '2022': row['2022'], '2023': row['2023'], 'Difference': row['Difference'] }) # 拆分Initial列的元素,逐个添加空数值行 for item in row['Initial'].split('/'): result_rows.append({ 'Type Label/Initial': item, '2022': None, '2023': None, 'Difference': None }) # 转换为最终DataFrame result_df = pd.DataFrame(result_rows) # 输出Markdown格式表格(若需导出可直接使用该结果) print(result_df.to_markdown(index=False))
代码说明
- 先构造或读取原始数据,确保
Initial列是用/分隔的字符串格式。 - 遍历每行数据,优先添加包含加粗
Type Label和对应数值的记录。 - 拆分
Initial列的字符串,为每个元素生成一行仅含标签、数值为空的记录。 - 将所有记录整合成新的DataFrame,通过
to_markdown输出符合要求的表格格式。
内容的提问来源于stack exchange,提问作者Mr Mann
相关产品推荐
相关产品推荐

