Python pandas如何对DataFrame按列、按行应用不同格式化规则
Pandas 行列差异化数据格式化方案
实现思路
- 对应用统一规则的
Delta列,直接做列级批量转换,全部输出为整数百分比格式 - 对需要按行匹配规则的Toyota、Honda销售绩效列,按行索引匹配对应格式化逻辑逐行处理,避免列级统一格式不符合行要求的问题
- 格式化规则严格匹配需求:
- Total Spend、Total Revenue行:千分位分隔的美元货币格式
- Total Sale Count行:千分位分隔的整数
- Present-Value/Sale行:整数百分比格式
完整可运行代码
import pandas as pd # 初始化原始数据集 data = {'Toyota Sales Performance': [500000.0000, 150000.0000, 100.0000, .2500], 'Honda Sales Performance': [750000.0000, 100000.0000, 200.0000, .3500], 'Delta': [.25, .35, .50, .75]} df = pd.DataFrame(data, index=['Total Spend', 'Total Revenue', 'Total Sale Count', 'Present-Value/Sale']) # 处理Delta列:统一转换为整数百分比 df['Delta'] = df['Delta'].apply(lambda x: f"{round(x*100)}%") # 逐行处理两个销售绩效列 sales_columns = ['Toyota Sales Performance', 'Honda Sales Performance'] for row_name in df.index: if row_name in ('Total Spend', 'Total Revenue'): # 美元货币格式 for col in sales_columns: df.loc[row_name, col] = f"${df.loc[row_name, col]:,.0f}" elif row_name == 'Total Sale Count': # 整数格式 for col in sales_columns: df.loc[row_name, col] = int(df.loc[row_name, col]) elif row_name == 'Present-Value/Sale': # 百分比格式 for col in sales_columns: df.loc[row_name, col] = f"{round(df.loc[row_name, col]*100)}%"
输出结果
运行代码后得到的DataFrame和预期效果完全一致:
| 行索引 | Toyota Sales Performance | Honda Sales Performance | Delta |
|---|---|---|---|
| Total Spend | $500,000 | $750,000 | 25% |
| Total Revenue | $150,000 | $100,000 | 35% |
| Total Sale Count | 100 | 200 | 50% |
| Present-Value/Sale | 25% | 35% | 75% |
如果只是需要在Jupyter等环境做展示格式化、不需要修改单元格实际存储值,也可以用pandas的
StylerAPI实现同样的显示效果,不会修改原始数值类型,适合做报表输出场景。
内容的提问来源于stack exchange,提问作者Thomas Marzol
相关产品推荐
相关产品推荐

