How can I format a float to separate by thousands, inverting dot and commas?

我的梦境 提交于 2020-03-20 21:08:13

问题


How can I format a float, from a pandas dataframe, to separate thousands by dots and commas, instead by commas and dots? ?

Input:

112299420.40

Actual output:

112,299,420.40

Required output:

112.299.420,40

My code:

pd.set_option('display.float_format', lambda x: '{:,.2f}'.format(x) if abs(x) < 10000 else '{:,.0f}'.format(x))

How can I change this piece of code to produce the required output?

I've tried to change it the intuitive way, but without success...

From: '{:,.2f}'

To: '{:.,2f}'


回答1:


Python 2.7 string formatting features don't seem to help in this case. However, you can use the locale module and set your locale to a country/language which uses the thousands/decimal separators you want (in the example below, Brazilian Portuguese):

import locale
locale.setlocale(locale.LC_ALL, 'pt_br.utf-8')
pd.set_option('display.float_format', lambda x: locale.format('%.2f', x, grouping=True))

Example:

In [45]: pd.Series([1111.15, 123456.78])
Out[45]:
0     1.111,15
1   123.456,78
dtype: float64

If you want to ignore decimals for numbers under 10000 (as it looks like from your code):

In [49]: pd.set_option('display.float_format', lambda x: locale.format('%.2f', x, grouping=True) if abs(x)>10000 else locale.format('%.0f', x))

In [50]: s
0         1111
1   123.456,78
dtype: float64


来源:https://stackoverflow.com/questions/35660823/how-can-i-format-a-float-to-separate-by-thousands-inverting-dot-and-commas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!