使用 pandas 在Excel中写入百分比 [英] Writing Percentages in Excel Using Pandas

查看:141
本文介绍了使用 pandas 在Excel中写入百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用熊猫之前写入csv时,我经常会使用以下格式的百分比:

 '%0.2f% %'%(x * 100)

这将在加载csv时正确处理Excel。 / p>

现在,我试图使用Pandas的to_excel函数并使用

 (simulation * 100。)to_excel(writer,'Simulated',float_format ='%0.2f %%')

并得到一个ValueError:无效的文字为float():0.0126%。没有'%%'它写得很好,但没有格式化为百分比。



有没有办法在Pandas的to_excel中写百分比?

解决方案

您可以执行以下解决方法:

  df * = 100 
df = pandas.DataFrame(df,dtype = str)
df + ='%'

ew = pandas.ExcelWriter('test .xlsx')
df.to_excel(ew)
ew.save()


When writing to csv's before using Pandas, I would often use the following format for percentages:

'%0.2f%%' % (x * 100)

This would be processed by Excel correctly when loading the csv.

Now, I'm trying to use Pandas' to_excel function and using

(simulated * 100.).to_excel(writer, 'Simulated', float_format='%0.2f%%')

and getting a "ValueError: invalid literal for float(): 0.0126%". Without the '%%' it writes fine but is not formatted as percent.

Is there a way to write percentages in Pandas' to_excel?

解决方案

You can do the following workaround in order to accomplish this:

df *= 100
df = pandas.DataFrame(df, dtype=str)
df += '%'

ew = pandas.ExcelWriter('test.xlsx')
df.to_excel(ew)
ew.save()

这篇关于使用 pandas 在Excel中写入百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆