使用 Pandas DataFrame 中的 float_format 调用 to_string 函数出现问题

4

当使用 pandasDataFrame 时,我可以在数据框上调用 to_string(float_format='%.1f')。但是,当尝试在 df.describe() 上应用相同的方法时,它会失败。

以下代码可以清楚地解释问题。

>>> df = pd.DataFrame([[1, 2, 'March'],[5, 6, 'Dec'],[3, 4, 'April'], [0, 1, 'March']], columns=['a','b','m']) 
>>> df
   a  b      m
0  1  2  March
1  5  6    Dec
2  3  4  April
3  0  1  March
>>> df.to_string(float_format='%.1f')
u'   a  b      m\n0  1  2  March\n1  5  6    Dec\n2  3  4  April\n3  0  1  March'
>>> df.describe().to_string(float_format='%.1f')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/pandas/core/frame.py", line 1343, in to_string
    formatter.to_string()
  File "/Library/Python/2.7/site-packages/pandas/core/format.py", line 511, in to_string
    strcols = self._to_str_columns()
  File "/Library/Python/2.7/site-packages/pandas/core/format.py", line 439, in _to_str_columns
    fmt_values = self._format_col(i)
  File "/Library/Python/2.7/site-packages/pandas/core/format.py", line 693, in _format_col
    space=self.col_space
  File "/Library/Python/2.7/site-packages/pandas/core/format.py", line 1930, in format_array
    return fmt_obj.get_result()
  File "/Library/Python/2.7/site-packages/pandas/core/format.py", line 1946, in get_result
    fmt_values = self._format_strings()
  File "/Library/Python/2.7/site-packages/pandas/core/format.py", line 2022, in _format_strings
    fmt_values = [self.formatter(x) for x in self.values]
TypeError: 'str' object is not callable
1个回答

9

第一次运行时它是有效的,因为您的类型中没有浮点数。您可以使用df.dtypes进行检查:

In [37]: df.dtypes
Out[37]: 
a     int64
b     int64
m    object
dtype: object

来自文档:

float_format : 一参数函数,可选
如果列的元素是浮点数,则应用于它们的格式化程序函数,默认为None。此函数的结果必须是Unicode字符串。

因此,您需要传递一个函数而不是字符串:

df.describe().to_string(float_format=lambda x: '%.1f' % x)

或者使用.format

df.describe().to_string(float_format=lambda x: "{:.1f}".format(x))

1
不错。我没有意识到这一点。在 to_string 中,float_format 是一个函数,而在 to_csv 中,float_format 是一个字符串。 - Causality

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接