gpt4 book ai didi

python - pandas to_csv 参数 float_format 为百分比

转载 作者:太空宇宙 更新时间:2023-11-03 21:29:25 33 4
gpt4 key购买 nike

我正在尝试输出 pandas 数据框,但我希望它以百分比形式输出 float 。我已经对此进行了大量搜索,并且我可以使它们在输出中显示为 float ,就像我想要的那样使用

pd.options.display.float_format = '{:,.2%}'.format

但我想要做的是完全相同的事情,除非我使用 .to_csv 方法导出到 .csv。

示例代码:

df2 = pd.DataFrame(data = {'Index': ['One', 'Two'], 'col1': [.1, .2], 'col2': [.3, .4], 'col3': [1, 7]})
df2.set_index('Index')

df:

    col1    col2    col3
Index
One 0.1 0.3 1
Two 0.2 0.4 7

col1 和 col2 是 float64,col3 是整数

我想使用以下内容(当然也可以使用类似的内容):

dfs.to_csv("filelocation and name.csv", float_format = '{:.2%}'.format)

输出到如下所示的 .csv:

    col1    col2    col3
Index
One 10% 30% 1
Two 20% 40% 7

任何帮助将不胜感激。我遇到了从“TypeError:不支持的格式字符串传递给 numpy.ndarray._ _ format _ _”到“KeyError:'%'”以及中间的一些错误。

最佳答案

您可以使用float_format来格式化csv文件中的输出,但这只是一个字符串,这意味着您可以格式化列,但不能对其进行操作他们。例如

with open('foo.csv', 'w') as f:
df2.to_csv(f, index = False, header = True, float_format = '%.2f%%')

将创建此输出

Index,col1,col2,col3
One,0.10%,0.30%,1
Two,0.20%,0.40%,7

如果您想更改值,我建议您在输出之前更新数据框

df2 = pandas.DataFrame(data = {'Index': ['One', 'Two'], 'col1': [.1, .2], 'col2': [.3, .4], 'col3': [1, 7]})
df2.set_index('Index')

df2['col1'] *= 100
df2['col2'] *= 100

with open('foo.csv', 'w') as f:
df2.to_csv(f, index = False, header = True, float_format = '%.2f%%')

关于python - pandas to_csv 参数 float_format 为百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53620542/

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