Pandas实现带欧元符号、自定义千分位与小数分隔符的数值格式化
数值欧元格式化问题
需求
需要将float类型数值按以下规则格式化:
- 千分位分隔符为点号(
.) - 小数分隔符为逗号(
,) - 始终显示两位小数
- 添加欧元符号(
€)
现有代码及结果
现有代码:
import pandas as pd df = pd.DataFrame({'x': [1.50, 2.3456, 10000.22, 100.3, 6800]}) df['x'].map('{:.2f} €'.format)
运行结果:
0 1.50 € 1 2.35 € 2 10000.22 € 3 100.30 € 4 6800.00 € Name: x, dtype: object
期望结果
0 1,50 € 1 2,35 € 2 10.000,22 € 3 100,30 € 4 6.800,00 € Name: x, dtype: object
解决方案
方法1:利用locale模块适配欧元区格式
欧元区(如德语区)的数值格式正好符合需求,可以通过locale模块直接调用对应区域的格式化规则:
import pandas as pd import locale # 配置区域(不同系统写法可能有差异:Linux用'de_DE.UTF-8',Windows用'de_de') locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8') df = pd.DataFrame({'x': [1.50, 2.3456, 10000.22, 100.3, 6800]}) # 调用locale的格式化函数,自动处理千分位和小数分隔符 df['formatted_x'] = df['x'].map(lambda num: f"{locale.format_string('%.2f', num, grouping=True)} €") print(df['formatted_x'])
注意:如果系统缺少对应区域包,Linux下需先安装(如language-pack-de),Windows通常自带。
方法2:自定义格式化函数(不依赖系统环境)
如果不想依赖系统区域设置,可手动实现格式转换逻辑:
import pandas as pd def format_euro(num): # 先格式化为两位小数的字符串 raw_str = '{:.2f}'.format(num) # 拆分整数与小数部分 integer_part, decimal_part = raw_str.split('.') # 给整数部分添加千分位点号:逆序后每三位拆分,再逆序拼接 grouped_integer = '.'.join([ integer_part[::-1][i:i+3][::-1] for i in range(0, len(integer_part), 3) ][::-1]) # 拼接最终格式 return f'{grouped_integer},{decimal_part} €' df = pd.DataFrame({'x': [1.50, 2.3456, 10000.22, 100.3, 6800]}) df['formatted_x'] = df['x'].map(format_euro) print(df['formatted_x'])
这个方法兼容性更强,无需依赖系统区域配置,直接通过字符串操作实现需求格式。
内容的提问来源于stack exchange,提问作者E. Sommer
相关产品推荐
相关产品推荐

