2013-08-23 44 views
15

對於Python新手,我最近發現,與PY 2.7我可以這樣做:PY熊貓.format(數據幀)

print '{:20,.2f}'.format(123456789) 

,這將給生成的輸出:

123,456,789.00 

我現在正有類似的結果對大熊貓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) 

在這種情況下,我有錯誤:

Unknown format code 'f' for object of type 'str' 

任何關於執行如'{:20,.2f}'.format(df)之類的建議的建議?現在我的想法是索引數據框(它是一個小的),然後格式化每個單獨的浮點數,可能會分配astype(str),並重建DF ...但看起來很醜陋: - (並且我甚至不確定它會工作...

你覺得怎麼樣?我卡住了...並且想要在這些轉換爲reportlabs網格時爲我的數據框提供更好的格式。

回答

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) 

產率(隨機類似於輸出)

     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_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. 
+0

非常感謝你爲這個!看起來很完美:-)的數據幀。這是一個很大的進步..現在我面臨的是關於reportlab的下一個主題..哈哈..有趣..當DF轉換爲網格,然後我顯然將失去格式.. uffff ....但我會以某種方式處理..很好的幫助!非常感謝 !! –

+3

也可以這樣做:'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 –

+0

@AndyHayden:感謝您的提示! – unutbu