2014-09-05 350 views
1

我有一個帶有異構數據的pandas DataFrame。這意味着一些列浮動,一些是字符串等pandas to_excel()使用float_format參數 - > ValueError:無法將字符串轉換爲浮點數

我首先嚐試通過調用xlsxwriter工作表級別set_column()方法格式化列,但它似乎to_excel()格式化每個單獨的單元格與它自己的格式對象,所以列級格式正在被覆蓋。

我想將一個DataFrame導出到Excel,並利用記錄的float_format參數here

代碼:

writer = pd.ExcelWriter(path, engine='xlsxwriter') 

ff = '_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)' 

df.to_excel(writer, "sheet_name", index=False, float_format=ff) 

我在調用時to_excel越來越例外:

$VE_DIR/lib/python2.7/site-packages/pandas/util/decorators.pyc in wrapper(*args, **kwargs) 
    58     else: 
    59      kwargs[new_arg_name] = old_arg_value 
---> 60    return func(*args, **kwargs) 
    61   return wrapper 
    62  return _deprecate_kwarg 

$VE_DIR/lib/python2.7/site-packages/pandas/core/frame.pyc in to_excel(self, excel_writer, sheet_name, na_rep, float_format, columns, header, index, index_label, startrow, startcol, engine, merge_cells, encoding, inf_rep) 
    1228   formatted_cells = formatter.get_formatted_cells() 
    1229   excel_writer.write_cells(formatted_cells, sheet_name, 
-> 1230         startrow=startrow, startcol=startcol) 
    1231   if need_save: 
    1232    excel_writer.save() 

$VE_DIR/lib/python2.7/site-packages/pandas/io/excel.pyc in write_cells(self, cells, sheet_name, startrow, startcol) 
    785   style_dict = {} 
    786 
--> 787   for cell in cells: 
    788    num_format_str = None 
    789    if isinstance(cell.val, datetime.datetime): 

$VE_DIR/lib/python2.7/site-packages/pandas/core/format.pyc in get_formatted_cells(self) 
    1729   for cell in itertools.chain(self._format_header(), 
    1730          self._format_body()): 
-> 1731    cell.val = self._format_value(cell.val) 
    1732    yield cell 
    1733 

$VE_DIR/lib/python2.7/site-packages/pandas/core/format.pyc in _format_value(self, val) 
    1510     val = self.inf_rep 
    1511    elif self.float_format is not None: 
-> 1512     val = float(self.float_format % val) 
    1513   return val 
    1514 

ValueError: could not convert string to float: _(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_) 

我會假設to_excel()將只嘗試應用到參數浮動格式的列(甚至特定的單元格),而不是每一塊數據,所以我不確定我錯過了什麼。如果需要的話,我會發布重現錯誤的特定表格的清理版本,但我想也許有人會認識到我面臨的是什麼。

謝謝!

回答

3

您的ff是完全無效的。看看這個:

val = float(self.float_format % val) 

現在試試這個(在IPython中或東西):

'_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)' % 7.2 

您需要使用浮點格式蟒蛇,不擅長

+1

感謝@acushner;這是一個根本的誤解......我試圖專門用千分隔符格式化,如[this](http://stackoverflow.com/questions/5513615/add-thousands-separators-to-a-number)雖然,並沒有得到承認。那裏有任何想法? – HaPsantran 2014-09-05 19:45:16

+0

'('{0:,}'。format(100000000))。replace(',','。')' – acushner 2014-09-08 13:06:34

+0

謝謝,但我想在熊貓中進行格式設置,以便浮點格式化爲生成電子表格。有沒有辦法? – HaPsantran 2014-09-09 17:07:58

相關問題