【发布时间】:2014-07-23 23:17:18
【问题描述】:
我正在尝试使用'{:,}'.format(number) 像下面的示例来格式化熊猫数据框中的数字:
# This works for floats and integers
print '{:,}'.format(20000)
# 20,000
print '{:,}'.format(20000.0)
# 20,000.0
问题在于,具有整数的数据帧不起作用,而具有浮点数的数据帧可以正常工作。查看示例:
# 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>
我做错了什么?
【问题讨论】:
-
我不知道为什么它不适用于整数,但你不能使用浮点数并指定精度,如
{:,.0f}? -
你需要为int指定一个单独的格式化程序;例如,请参阅this 问题。
-
但在那个问题中,他使用了与我使用的相同格式
int_frmt = lambda x: '{:,}'.format( x )