When using pandas
DataFrame
, I can do to_string(float_format='%.1f')
on a DataFrame
. However, when applying the same method to df.describe()
, it failed.
The issue is self-explanatory with the following code.
>>> 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
It's working in your first time because none of your types are float. You could check that with df.dtypes
:
In [37]: df.dtypes
Out[37]:
a int64
b int64
m object
dtype: object
From docs:
float_format : one-parameter function, optional
formatter function to apply to columns’ elements if they are floats, default None. The result of this function must be a unicode string.
So you need to pass a function not a string:
df.describe().to_string(float_format=lambda x: '%.1f' % x)
or with .format
:
df.describe().to_string(float_format=lambda x: "{:.1f}".format(x))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With