【问题标题】:pandas df - calculate percentage difference not changepandas df - 计算百分比差异不变
【发布时间】:2019-02-18 13:32:15
【问题描述】:

我想计算百分比差异不变或只是两个值之间的差异。

我的 df:

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

预期输出:

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

计算如下:

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

【问题讨论】:

  • df.series.diff() ?
  • 只给我两个值之间的差异,不计算百分比差异
  • 对不起,我关闭错误,之前没有测试过。谢谢你的公式。
  • 谢谢!我现在正在检查。

标签: python pandas


【解决方案1】:

将差值除以diff 与绝对值除以abs 与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

如果需要百分比:

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

【讨论】:

    猜你喜欢
    • 2020-11-27
    • 2021-06-17
    • 2021-01-05
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    相关资源
    最近更新 更多