Py Pandas .format(数据框) [英] Py Pandas .format(dataframe)
问题描述
作为Python新手,我最近发现使用Py 2.7,我可以执行以下操作:
As Python newbie I recently discovered that with Py 2.7 I can do something like:
print '{:20,.2f}'.format(123456789)
这将给出结果输出:
123,456,789.00
现在我想看一下熊猫df的结果,所以我的代码如下:
I'm now looking to have a similar outcome for a pandas df so my code was like:
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'
任何建议执行类似{:20,.2f}的格式(df)?
Any suggestions to perform something like '{:20,.2f}'.format(df) ?
现在我的想法是索引数据帧(它是一个小的),然后格式化其中的每个单独的浮点数,可能会分配astype(str ),并重建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 ..
你觉得怎么样?我被卡住了,并且希望在将这些格式转换成reportlabs网格时,为我的数据帧提供更好的格式。
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.
非常感谢你,Fabio。 p>
Thank you so much, Fabio.
推荐答案
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)
yield(random output similar to)
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
pd.set_option $ c的docstring $ c>或
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.
这篇关于Py Pandas .format(数据框)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!