我在下面的数据框中获取上个月的数据并获取百分比。
我得到的百分比输出如下:
码:
current = df['August']
previous = df['September']
per=[]
for a, b in zip(current, previous):
try:
per.append(round((((a - b) / a) * 100.0)))
except ZeroDivisionError:
per.append(0)
输出
[0, 25, 54, 0, 0, 0, -22, 100, 0, 0, 38, 0, 100, -117, 0, 0, 100, 1, 0, -377, 37]
预期输出以及“%”符号,例如:
[0%, 25%, 54%, 0%, 0%, 0%, -22%, 100%, 0%, 0%, 38%, 0%, 100%, -117%, 0%, 0%, 100%, 1%, 0%, -377%, 37%]
如果您需要在其中添加“%” float
,则需要将其转换为str
因此,我的建议是:
for a, b in zip(current, previous):
try:
#Add this two new lines
x = repr((a - b) / a * 100.0)
per.append(x + "%")
#Do not need this
#per.append(round((((a - b) / a) * 100.0)))
except ZeroDivisionError:
per.append(0)
打印出print(per)
收益:
['50.0%']
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句