Python3 - np.histogram 输出小数问题

Python3 - np.histogram output decimal issue

我是 python 的新手,我有很多数字的列表,然后我想使用 np.histogram & pandas 生成像 csv 文件一样的直方图:

import numpy as np
import pandas as pd

counts, bin_edges = np.histogram(data, bins=5)
print(counts)
print(bin_edges)

我得到以下输出:

[27 97 24 27 11]
[-19.12   -8.406   2.308  13.022  23.736  34.45 ]

然后我尝试将数据写入CSV文件

bin = 5
min = np.delete(bin_edges, bin)
max = np.delete(bin_edges, 0)

df = pd.DataFrame({'Min': min, 'Max': max, 'Count': counts})
df.to_csv('data.csv', index=False, sep='\t')

但是,我得到了以下文件...

Min Max Count
-19.12  -8.405999999999999  27
-8.405999999999999  2.3080000000000034  97
2.3080000000000034  13.02200000000001   24
13.02200000000001   23.736000000000008  27
23.736000000000008  34.45   11

有什么方法可以限制十进制数吗?

非常感谢,

您可以使用 to_csv() 函数的 float_format 参数。

df.to_csv(
  'data.csv',
  index=False,
  sep='\t',
  float_format='%.3f')

在上面的示例中,输出是小数点后 3 位。有关详细信息,请参阅 pandas docs and the python docs