【问题标题】:Calculate ratio (starting value of year/ending value of previous year) in multi-index dataframe计算多指标数据框中的比率(年初值/上年结束值)
【发布时间】:2019-06-11 21:01:10
【问题描述】:

作为对发送的年度报告的合理性检查,我想根据上一年提交的期末值确保一年的陈述值是正确的。通过这个多索引数据框,我尝试解释我的问题:

import random
col3=[0,0,0,0,2,4,6,0,0,0,100,200,300,400]
col4=[0,0,0,0,4,6,8,0,0,0,200,900,400, 500]

d = {'Unit': [1, 1, 1, 1, 2, 2, 2, 3, 4, 5, 6, 6, 6, 6], 
 'Year': [2014, 2015, 2016, 2017, 2015, 2016, 2017, 2017, 2014, 2015, 2014, 2015, 2016, 2017], 'col3' : col3, 'col4' : col4 }
df = pd.DataFrame(data=d)
df.groupby(['Unit', 'Year']).sum()

我想要做的是创建一个带有比率的附加列。例如:Unit 2 year 2016 col3/ Unit 2 year 2015 col 4 = 4/4 = 1。我的下一步是查看比率是否为 1。我在此数据框中放置了一个示例,其中比率不是 1 .这原则上是我感兴趣的案例,我想确定那个数据点。

我遇到的一个问题是我的数据框中有很多零。

感谢您的任何意见!

【问题讨论】:

    标签: python pandas dataframe multi-index


    【解决方案1】:

    IIUC,你可以在 groupby 上应用一个函数:

    new_df = df.groupby(['Unit', 'Year']).sum()
    
    new_df['mask'] = (new_df.groupby(level=0, group_keys=False)
                      .apply(lambda x: x.col3/x.col4.shift())
                     )
    

    那么你的new_df 看起来像这样:

               col3  col4      mask
    Unit Year                      
    1    2014     0     0       NaN
         2015     0     0       NaN
         2016     0     0       NaN
         2017     0     0       NaN
    2    2015     2     4       NaN
         2016     4     6  1.000000
         2017     6     8  1.000000
    3    2017     0     0       NaN
    4    2014     0     0       NaN
    5    2015     0     0       NaN
    6    2014   100   200       NaN
         2015   200   900  1.000000
         2016   300   400  0.333333
         2017   400   500  1.000000
    

    你可以fillna或者过滤那些不等于1的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多