问题描述
如何格式化来自熊猫数据框的浮点数,以点和逗号分隔数千个,而不是逗号和点分隔? ?
How can I format a float, from a pandas dataframe, to separate thousands by dots and commas, instead by commas and dots? ?
输入:
112299420.40
实际输出:
112,299,420.40
必填输出:
112.299.420,40
我的代码:
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...
发件人: '{:,.2f}'
收件人: '{:.,2f}'
推荐答案
在这种情况下,Python 2.7字符串格式设置功能似乎无济于事.但是,您可以使用locale
模块并将语言环境设置为使用所需的千位/十进制分隔符的国家/地区(在下面的示例中为巴西葡萄牙语):
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))
示例:
In [45]: pd.Series([1111.15, 123456.78])
Out[45]:
0 1.111,15
1 123.456,78
dtype: float64
如果您要忽略10000以下数字的小数(从代码中看起来是这样):
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
这篇关于如何格式化浮点数,以成千上万的点,逗号和点分隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!