如何在使用 pandas 或任何 python 模块计算时获取单元格中的百分比符号
How to get the Percentage symbol in cell while calculating using pandas or any python module
我在下面有一个数据框,我在其中获取上个月的数据并获取百分比。
我得到的百分比输出如下:
代码:
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%']
我在下面有一个数据框,我在其中获取上个月的数据并获取百分比。
我得到的百分比输出如下:
代码:
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%']