pandasto_excel()使用float_format参数 – > ValueError:无法将string转换为浮动

我有一个pandasDataFrame异质数据。 这意味着一些列浮动,一些是string等。

我首先尝试通过调用xlsxwriter工作表级别的set_column()方法来格式化列,但似乎to_excel()使用它自己的格式对象格式化每个单独的单元格,所以列级格式将被覆盖。

我试图导出一个DataFrame到Excel,并利用这里logging的float_format参数。

代码:

writer = pd.ExcelWriter(path, engine='xlsxwriter') ff = '_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)' df.to_excel(writer, "sheet_name", index=False, float_format=ff) 

我正在调用to_excel的exception:

 $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()只会尝试将参数应用于浮动格式的列(或甚至特定的单元格),而不是每一块数据,所以我不知道我错过了什么。 如果需要的话,我会发布一个清晰的表格来重现错误,但我想也许有人会认识到我面临的是什么。

谢谢!

你的ff是完全无效的。 看这个:

 val = float(self.float_format % val) 

现在尝试这个(在ipython或其他):

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

你需要使用python的float格式,而不是excel