格式化大 pandas 数据框中的整数的千位分隔符 [英] Formatting thousand separator for integers in a pandas dataframe
本文介绍了格式化大 pandas 数据框中的整数的千位分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正尝试使用'{:,}'.format(number)
像下面的示例一样在熊猫数据框中格式化数字:
I'm trying to use '{:,}'.format(number)
like the example below to format a number in a pandas dataframe:
# This works for floats and integers
print '{:,}'.format(20000)
# 20,000
print '{:,}'.format(20000.0)
# 20,000.0
问题在于,具有整数的数据帧不起作用,而具有浮点数的数据帧可以正常工作.请参见示例:
The problem is that with a dataframe that has integers does not work, and in a dataframe with float works ok. See the examples:
# 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>
我做错了什么?
推荐答案
to_html
中的formatters
参数将采用映射到格式函数的列名字典.以下是构建dict的函数示例,该dict将相同的函数映射到float和int.
The formatters
parameter in to_html
will take a dictionary of column names mapped to a formatting function. Below has an example of a function to build a dict that maps the same function to both floats and ints.
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>
这篇关于格式化大 pandas 数据框中的整数的千位分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文