gpt4 book ai didi

python - 在 Pandas DataFrame 上使用 float_format 调用 to_string 时出现问题

转载 作者:行者123 更新时间:2023-12-02 07:42:02 35 4
gpt4 key购买 nike

当使用pandasDataFrame ,我可以to_string(float_format='%.1f')DataFrame上。然而,当将相同的方法应用于 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

最佳答案

它在你第一次工作,因为你的类型都不是 float 的。您可以使用 df.dtypes 进行检查:

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

来自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.

所以你需要传递一个函数而不是字符串:

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

或使用.format:

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

关于python - 在 Pandas DataFrame 上使用 float_format 调用 to_string 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34097038/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com