在 Python pandas DataFrame 中为数字添加千位分隔符的简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41447383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Easy way to add thousand separator to numbers in Python pandas DataFrame
提问by thatMeow
Assuming that I have a pandas dataframe and I want to add thousand separators to all the numbers (integer and float), what is an easy and quick way to do it?
假设我有一个 Pandas 数据框并且我想为所有数字(整数和浮点数)添加千位分隔符,有什么简单快捷的方法可以做到?
回答by 2ps
When formatting a number with ,you can just use '{:,}'.format:
格式化数字时,,您可以使用'{:,}'.format:
n = 10000
print '{:,}'.format(n)
n = 1000.1
print '{:,}'.format(n)
In pandas, you can use the formattersparameter to to_htmlas discussed here.
在 Pandas 中,您可以使用这里讨论的formatters参数 to 。to_html
num_format = lambda x: '{:,}'.format(x)
def build_formatters(df, format):
return {
column:format
for column, dtype in df.dtypes.items()
if dtype in [ np.dtype('int64'), np.dtype('float64') ]
}
formatters = build_formatters(data_frame, num_format)
data_frame.to_html(formatters=formatters)
Adding the thousands separator has actually been discussed quite a bit on stackoverflow. You can read hereor here.
回答by lcvriend
Assuming you just want to display (or render to html) the floats/integers with a thousands separator you can use stylingwhich was added in version 0.17.1:
假设你只是想显示(或渲染HTML)彩车/有成千上万的整数分离器可以用造型这是在0.17.1版新增:
import pandas as pd
df = pd.DataFrame({'int': [1200, 320], 'flt': [5300.57, 12000000.23]})
df.style.format('{:,}')
To render this output to html you use the render method on the Styler.
要将此输出呈现为 html,您可以使用Styler.
回答by Pablo Vilas
If you want "." as thousand separator and "," as decimal separator this will works:
如果你想 ”。” 作为千位分隔符和“,”作为小数点分隔符,这将起作用:
Data = pd.read_Excel(path)
Data = pd.read_Excel(path)
Data[my_numbers] = Data[my_numbers].map('{:,.2f}'.format).str.replace(",", "~").str.replace(".", ",").str.replace("~", ".")
Data[my_numbers] = Data[my_numbers].map('{:,.2f}'.format).str.replace(",", "~").str.replace(".", ",").str.replace("~", ".")
If you want three decimals instead of two you change "2f" --> "3f"
如果您想要三位小数而不是两位小数,则更改“2f”->“3f”
Data[my_numbers] = Data[my_numbers].map('{:,.3f}'.format).str.replace(",", "~").str.replace(".", ",").str.replace("~", ".")
Data[my_numbers] = Data[my_numbers].map('{:,.3f}'.format).str.replace(",", "~").str.replace(".", ",").str.replace("~", ".")
回答by Ranadip Dutta
The formattersparameter in to_htmlwill take a dictionary.
to_html 中的formatters参数将采用字典。
回答by jezrael
Use Series.mapor Series.applywith this solutions:
使用Series.map或Series.apply与此解决方案一起使用:
df['col'] = df['col'].map('{:,}'.format)
df['col'] = df['col'].map(lambda x: f'{x:,}')
df['col'] = df['col'].apply('{:,}'.format)
df['col'] = df['col'].apply(lambda x: f'{x:,}')

