简体   繁体   中英

pandas df - calculate percentage difference not change

I want to calculate the percentage difference not change or just the difference between two values.

my df:

                           Radisson Collection      
6                                                                  
Total awareness             0.440553            
Very/Somewhat familiar      0.462577           
Consideration               0.494652             
Ever used                   0.484620           

Expected output:

                            Radisson Collection      
6                                                                  
Total awareness             none            
Very/Somewhat familiar      4.87726%           
Consideration               6.70163%            
Ever used                   2.04886%          

The calculation would be:

Difference of 0.440553 and 0.462577 = |0.440553 - 0.462577|/((0.440553 + 0.462577)/2) = 0.022024/0.451565 = 0.048772601950993 = 4.8772601950993%

Divide difference by diff with absolute values by abs with rolling mean :

s = df['Radisson Collection'].rolling(2).mean()
df['new'] = df['Radisson Collection'].diff().abs().div(s) * 100
print (df)
                        Radisson Collection       new
Total awareness                    0.440553       NaN
Very/Somewhat familiar             0.462577  4.877260
Consideration                      0.494652  6.701636
Ever used                          0.484620  2.048869

If need percentages:

df['new'] = (df['Radisson Collection'].diff().abs().div(s) * 100)
                    .iloc[1:].round(5).astype(str) + '%'

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