pandasto_csv参数float_format设置为百分比



我试图输出pandas数据帧,但我希望它以百分比形式输出浮点值。我已经对此进行了大量的搜索,我可以让它们在输出中显示为浮动,就像我使用一样

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,该.csv看起来像:

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

如有任何帮助,我们将不胜感激。我遇到了从"TypeError:传递给numpy.ndarray._format__的不受支持的格式字符串"到"KeyError:'%'"的错误,以及介于两者之间的一些错误。

您可以访问float_format来格式化csv文件中的输出,但这只是string,这意味着您可以格式化列,但不能对它们进行操作。例如

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%%')

最新更新