简体   繁体   English

在 Python pandas DataFrame 中为数字添加千位分隔符的简单方法

[英]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.mapSeries.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参数将采用字典。

Click the example link for reference 单击示例链接以供参考

Steps脚步

  • use df.applymap() to apply a function to every cell in your dataframe使用df.applymap()将函数应用于数据df.applymap()每个单元格
  • check if cell value is of type int or float检查单元格值是否为intfloat类型
  • format numbers using 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.

相关问题 XlsxWriter 带 Pandas dataframe 千位分隔符 - XlsxWriter with Pandas dataframe thousand separator 为熊猫数据帧中的整数格式化千位分隔符 - Formatting thousand separator for integers in a pandas dataframe Pandas 数据框中的舍入和千位分隔符:无法去掉小数 - Rounding and thousand separator in pandas dataframe: cannot get rid of decimal 如何将千位分隔符添加到 Javascript / Python / Django 中的数字 - How to add Thousand Separator to number in Javascript / Python / Django 如何将十进制和千位分隔符应用于cbar中的数字? - How to apply decimal and thousand separator to numbers in cbar? 使用千位分隔符格式化多个数据框列 - Format multiple dataframe columns with the thousand separator 有没有一种简单的方法可以在熊猫数据框中找到元素的“坐标”? - Is there an easy way to find the 'coordinates' of an element in a pandas dataframe? 使用千位分隔符格式化 Pandas 列 - Format Pandas columns with thousand space separator 有没有办法从 pandas dataframe 中使用 python 查找序列中缺失的数字? - Is there a way to find missing numbers in a sequence using in python from a pandas dataframe? 在 Python 中,有没有一种简单的方法可以以这种方式操作 dataframe? - In Python, is there an easy way to manipulate dataframe in this way?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM