当使用 pandas
的 DataFrame
时,我可以在数据框上调用 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
to_string
中,float_format
是一个函数,而在to_csv
中,float_format
是一个字符串。 - Causality