【问题标题】:Python3 - np.histogram output decimal issuePython3 - np.histogram 输出十进制问题
【发布时间】:2021-02-07 13:12:42
【问题描述】:

我是 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

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

非常感谢,

【问题讨论】:

    标签: python-3.x pandas numpy histogram


    【解决方案1】:

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

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

    在上面的示例中,输出为小数点后 3 位。请参阅pandas docspython docs 了解更多信息。

    【讨论】:

    • 感谢 Mullinscr。但是当我写入 csv 文件时如何保持“bin gap”相同?
    • 你能解释一下'bin gap'是什么意思吗?
    猜你喜欢
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 2014-01-22
    相关资源
    最近更新 更多