问题
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