[英]Easy way to add thousand separator to numbers in Python pandas DataFrame
假设我有一个 Pandas 数据框并且我想为所有数字(整数和浮点数)添加千位分隔符,有什么简单快捷的方法可以做到?
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 formatters
parameter to to_html
as discussed here .在熊猫,你可以使用formatters
参数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.添加千位分隔符实际上已经在 stackoverflow 上讨论了很多。 You can read here or here .你可以在这里或这里阅读。
Assuming you just want to display (or render to html) the floats/integers with a thousands separator you can use styling which 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
上的 render 方法。
Use Series.map
or Series.apply
with 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:,}')
If you want "."如果你想 ”。” as thousand separator and "," as decimal separator this will works:作为千位分隔符和“,”作为十进制分隔符,这将起作用:
Data = pd.read_Excel(path)
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("~", ".")
The formatters parameter in to_html will take a dictionary. to_html 中的formatters参数将采用字典。
Steps脚步
df.applymap()
to apply a function to every cell in your dataframe使用df.applymap()
将函数应用于数据df.applymap()
每个单元格int
or float
检查单元格值是否为int
或float
类型f'{x:,d}'
for integers and f'{x:,f}'
for floats使用f'{x:,d}'
表示整数格式化数字,使用f'{x:,d}'
f'{x:,f}'
表示浮点数Here is a simple example for integers only:这是一个仅适用于整数的简单示例:
df = df.applymap(lambda x: f'{x:,d}' if isinstance(x, int) else x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.