我正在尝试使用'{:,}'.format(number)下面的示例来格式化pandas数据帧中的数字:
# This works for floats and integers
print '{:,}'.format(20000)
# 20,000
print '{:,}'.format(20000.0)
# 20,000.0
Run Code Online (Sandbox Code Playgroud)
问题是,对于具有整数的数据帧不起作用,并且在具有float的数据框中工作正常.看看例子:
# Does not work. The format stays the same, does not show thousands separator
df_int = DataFrame({"A": [20000, 10000]})
print df_int.to_html(float_format=lambda x: '{:,}'.format(x))
# Example of result
# <tr>
# <th>0</th>
# <td> 20000</td>
# </tr
# Works OK
df_float = DataFrame({"A": [20000.0, 10000.0]})
print df_float.to_html(float_format=lambda x: '{:,}'.format(x))
# Example of result
# <tr>
# <th>0</th>
# <td>20,000.0</td>
# </tr>
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
kyn*_*nan 10
pandas(截至0.20.1)不允许以简单的方式覆盖默认的整数格式.它是硬编码的pandas.io.formats.format.IntArrayFormatter(labmda函数):
class IntArrayFormatter(GenericArrayFormatter):
def _format_strings(self):
formatter = self.formatter or (lambda x: '% d' % x)
fmt_values = [formatter(x) for x in self.values]
return fmt_values
Run Code Online (Sandbox Code Playgroud)
我假设您实际要求的是如何覆盖所有整数的格式:replace("monkey patch")IntArrayFormatter打印整数值,用逗号分隔数千,如下所示:
import pandas
class _IntArrayFormatter(pandas.io.formats.format.GenericArrayFormatter):
def _format_strings(self):
formatter = self.formatter or (lambda x: ' {:,}'.format(x))
fmt_values = [formatter(x) for x in self.values]
return fmt_values
pandas.io.formats.format.IntArrayFormatter = _IntArrayFormatter
Run Code Online (Sandbox Code Playgroud)
注意:
pandas.formats.format.pandas.core.format.对于浮动,你不需要跳过这些环,因为它有一个配置选项:
display.float_format:callable应接受浮点数并返回具有所需数字格式的字符串.这在某些地方使用过SeriesFormatter.请参阅core.format.EngFormatter示例.
该formatters参数to_html将映射到格式化函数列名称的字典.下面有一个函数的例子来构建一个dict,它将相同的函数映射到浮点数和整数.
In [250]: num_format = lambda x: '{:,}'.format(x)
In [246]: def build_formatters(df, format):
...: return {column:format
...: for (column, dtype) in df.dtypes.iteritems()
...: if dtype in [np.dtype('int64'), np.dtype('float64')]}
...:
In [247]: formatters = build_formatters(df_int, num_format)
In [249]: print df_int.to_html(formatters=formatters)
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>A</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>20,000</td>
</tr>
<tr>
<th>1</th>
<td>10,000</td>
</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)