简体   繁体   中英

How to get the Percentage symbol in cell while calculating using pandas or any python module

I have data-frame below where I am taking the previous month data and getting the percentage.

数据帧

Output which I get with the percentage is below:

code:

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)

output

[0, 25, 54, 0, 0, 0, -22, 100, 0, 0, 38, 0, 100, -117, 0, 0, 100, 1, 0, -377, 37]

Expecting output along with "%" symbol like:

[0%, 25%, 54%, 0%, 0%, 0%, -22%, 100%, 0%, 0%, 38%, 0%, 100%, -117%, 0%, 0%, 100%, 1%, 0%, -377%, 37%]

预期输出

If you need to add "%" to your float , it needs to be converted into str

So, my suggestion is:

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 out print(per) Yields:

['50.0%']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM