You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas将混合类型列格式化为百分比、货币或字符串?

Pandas对象列按内容自动格式化(百分比/货币/原字符串)

需求

将Pandas的object类型列根据内容自动格式化:

  • 若内容为小数,转换为百分比格式(保留0位小数)
  • 若内容为整数,转换为货币格式(带千分位、保留2位小数)
  • 其他内容保留原字符串

示例DataFrame

import pandas as pd

df = pd.DataFrame([[1000, 'Jerry', 'BR1','BR1','Between 0.23% - 0.32%',''], 
                    [1001, 'N/A', 'N/A', 'BR1','0.025',''], 
                    ['N/A', 'N/A', 'BR3', 'BR2','0.25',''],
                    [1003, 'Perry','BR4','BR1','20000','']],
                   columns=['ID', 'Name', 'Branch', 'Member of','Percent, Comment, or Value','Formatting'],
                   dtype='object')

原函数问题

原函数能正确识别整数并转为货币格式,但小数无法触发百分比格式化,最终返回原字符串:

def format_col(df):
    if str(df['Percent, Comment, or Value']).replace(".", "", 1).isnumeric():
        formatted_val = "{:.0%}". format(float(df['Percent, Comment, or Value']))
    if df['Percent, Comment, or Value'].isnumeric():
        formatted_val = "${:,.2f}".format(float(df['Percent, Comment, or Value']))
    else:
        formatted_val = df['Percent, Comment, or Value']

    return formatted_val

df['Formatting'] = df.apply(format_col, axis=1)

错误输出:

ID  Name Branch Member of Percent, Comment, or Value       Formatting
0  1000 Jerry    BR1       BR1  Between 0.23% - 0.32%  Between 0.23% - 0.32%
1  1001   N/A    N/A       BR1                    0.025                  0.025
2   N/A   N/A    BR3       BR2                     0.25                   0.25
3  1003 Perry    BR4       BR1                    20000           $20,000.00

问题根源:

  1. 两个独立的if语句导致小数场景下,先触发百分比格式化,但随后因第二个if不满足(小数字符串的.isnumeric()返回False),进入else分支覆盖了格式化结果,最终返回原字符串。
  2. 字符串判断逻辑存在漏洞,不如直接尝试数值转换更可靠。

修改后的函数

改用try-except尝试数值转换,先区分整数和小数,再处理非数值内容:

def format_col(row):
    val = row['Percent, Comment, or Value']
    try:
        # 尝试转换为浮点数
        num = float(val)
        # 判断是否为整数
        if num.is_integer():
            return "${:,.2f}".format(num)
        # 小数则转为百分比
        else:
            return "{:.0%}".format(num)
    # 无法转换为数值时返回原字符串
    except ValueError:
        return val

df['Formatting'] = df.apply(format_col, axis=1)

正确输出

ID  Name Branch Member of Percent, Comment, or Value       Formatting
0  1000 Jerry    BR1       BR1  Between 0.23% - 0.32%  Between 0.23% - 0.32%
1  1001   N/A    N/A       BR1                    0.025                    3%
2   N/A   N/A    BR3       BR2                     0.25                   25%
3  1003 Perry    BR4       BR1                    20000           $20,000.00

内容的提问来源于stack exchange,提问作者EA Bubnoff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 14:35:45