Py Pandas .format(dataframe)

Fab*_*omi 17 python format dataframe pandas

作为Python新手我最近发现使用Py 2.7我可以做类似的事情:

print '{:20,.2f}'.format(123456789)
Run Code Online (Sandbox Code Playgroud)

这将产生最终的输出:

123,456,789.00
Run Code Online (Sandbox Code Playgroud)

我现在想要为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)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我有错误:

 Unknown format code 'f' for object of type 'str'
Run Code Online (Sandbox Code Playgroud)

有什么建议'{:20,.2f}'.format(df)吗?

现在我的想法是索引数据框(它是一个小的),然后格式化其中的每个浮动,可能分配astype(str),并重建DF ......但看起来很丑陋:-(和我'我甚至不确定它会起作用..

你怎么看 ?我被卡住了...并希望在将这些数据帧转换为reportlabs网格时为我的数据帧提供更好的格式.

unu*_*tbu 24

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)
Run Code Online (Sandbox Code Playgroud)

收益率(随机输出类似)

                     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
Run Code Online (Sandbox Code Playgroud)

文档字符串pd.set_optionpd.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.
Run Code Online (Sandbox Code Playgroud)

  • 也可以这样做`pd.options.display.float_format ='{:20,.2f}'.format`或`pd.set_option('float_format','{:20,.2f}'.format)`: )http://pandas.pydata.org/pandas-docs/stable/basics.html#working-with-package-options (3认同)