tha*_*eow 2 python separator number-formatting pandas
假设我有一个pandas数据框,并且想对所有数字(整数和浮点数)添加千位分隔符,那么有什么简便快捷的方法呢?
假设您只想显示(或渲染为 html)带有千位分隔符的浮点数/整数,您可以使用版本 0.17.1 中添加的样式:
import pandas as pd
df = pd.DataFrame({'int': [1200, 320], 'flt': [5300.57, 12000000.23]})
df.style.format('{:,}')
Run Code Online (Sandbox Code Playgroud)
要将此输出呈现为 html,您可以使用Styler.
使用Series.map或Series.apply与此解决方案一起使用:
df['col'] = df['col'].map('{:,}'.format)
df['col'] = df['col'].map(lambda x: f'{x:,}')
Run Code Online (Sandbox Code Playgroud)
df['col'] = df['col'].apply('{:,}'.format)
df['col'] = df['col'].apply(lambda x: f'{x:,}')
Run Code Online (Sandbox Code Playgroud)
使用格式化数字时,,您可以使用'{:,}'.format:
n = 10000
print '{:,}'.format(n)
n = 1000.1
print '{:,}'.format(n)
Run Code Online (Sandbox Code Playgroud)
在熊猫中,您可以按照此处的说明使用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)
Run Code Online (Sandbox Code Playgroud)
实际上,已经在stackoverflow上讨论了添加千位分隔符的问题。您可以在这里或这里阅读。
| 归档时间: |
|
| 查看次数: |
6069 次 |
| 最近记录: |