Py Pandas .format(dataframe)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/18404946/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Py Pandas .format(dataframe)
提问by Fabio Pomi
As Python newbie I recently discovered that with Py 2.7 I can do something like:
作为 Python 新手,我最近发现使用 Py 2.7 我可以执行以下操作:
print '{:20,.2f}'.format(123456789)
which will give the resulting output:
这将给出结果输出:
123,456,789.00
I'm now looking to have a similar outcome for a pandas df so my code was like:
我现在希望为 Pandas df 提供类似的结果,所以我的代码如下:
import pandas as pd
import random
data = [[random.random()*10000 for i in range(1,4)] for j in range (1,8)]
df = pd.DataFrame (data)
print '{:20,.2f}'.format(df)
In this case I have the error:
在这种情况下,我有错误:
 Unknown format code 'f' for object of type 'str'
Any suggestions to perform something like '{:20,.2f}'.format(df)?
有什么建议可以执行类似的操作'{:20,.2f}'.format(df)吗?
As now my idea is to index the dataframe (it's a small one), then format each individual float within it, might be assign astype(str), and rebuild the DF ... but looks so looks ugly :-( and I'm not even sure it'll work ..
现在我的想法是索引数据帧(它是一个小数据帧),然后格式化其中的每个单独的浮点数,可能会分配 astype(str),然后重建 DF ......但看起来很丑:-( 而且我'我什至不确定它会起作用..
What do you think ? I'm stuck ... and would like to have a better format for my dataframes when these are converted to reportlabs grids.
你怎么认为 ?我被卡住了……当我的数据框被转换为 reportlabs 网格时,我想为我的数据框提供更好的格式。
回答by unutbu
import pandas as pd
import numpy as np
data = np.random.random((8,3))*10000
df = pd.DataFrame (data)
pd.options.display.float_format = '{:20,.2f}'.format
print(df)
yields (random output similar to)
产量(随机输出类似于)
                     0                    1                    2
0             4,839.01             6,170.02               301.63
1             4,411.23             8,374.36             7,336.41
2             4,193.40             2,741.63             7,834.42
3             3,888.27             3,441.57             9,288.64
4               220.13             6,646.20             3,274.39
5             3,885.71             9,942.91             2,265.95
6             3,448.75             3,900.28             6,053.93
The docstring for pd.set_optionor pd.describe_optionexplains:
用于pd.set_option或pd.describe_option解释的文档字符串:
display.float_format: [default: None] [currently: None] : callable
        The callable should accept a floating point number and return
        a string with the desired format of the number. This is used
        in some places like SeriesFormatter.
        See core.format.EngFormatter for an example.

