【问题标题】:Multiply top h values times k for each row in a dataframe python将数据框python中每一行的前h值乘以k
【发布时间】:2019-03-26 16:28:45
【问题描述】:

我有一个数据框,其中包含一些日期作为行和列中的值。要知道 df 如下所示:

            c1  c2  c3  c4
12/12/2016  38  10   1   8
12/11/2016  44  12  17  46
12/10/2016  13   6   2   7
12/09/2016   9  16  13  26

我正在尝试找到一种方法来遍历每一行并仅将前 2 个值乘以 k = 3。结果应该在现有 df 的新列中。任何建议或提示都非常感谢!

谢谢!

【问题讨论】:

  • 我真的很抱歉我忘了说要创建的新列是前 2 个值乘以 3 的总和。对于第一行 '12/12/2016' 我应该得到 ( 38*3)+(8*3) = 138 再次抱歉之前没有指定。
  • 是的!很抱歉造成混乱,绝对是 (38*3)+(10*3) = 144

标签: python pandas loops top-n


【解决方案1】:

groupby + nlargest 之后使用update

df.update(df.stack().groupby(level=0).nlargest(2).mul(k).reset_index(level=0,drop=True).unstack())
df
Out[1036]: 
               c1    c2  c3     c4
12/12/2016  114.0  30.0   1    8.0
12/11/2016  132.0  12.0  17  138.0
12/10/2016   39.0   6.0   2   21.0
12/09/2016    9.0  48.0  13   78.0

【讨论】:

    【解决方案2】:

    nlargest

    df.assign(newcol=df.apply(sorted, 1).iloc[:, -2:].sum(1) * 3)
    
                c1  c2  c3  c4  newcol
    12/12/2016  38  10   1   8     144
    12/11/2016  44  12  17  46     270
    12/10/2016  13   6   2   7      60
    12/09/2016   9  16  13  26     126
    

    partition

    df.assign(newcol=np.partition(df, -2)[:, -2:].sum(1) * 3)
    
                c1  c2  c3  c4  newcol
    12/12/2016  38  10   1   8     144
    12/11/2016  44  12  17  46     270
    12/10/2016  13   6   2   7      60
    12/09/2016   9  16  13  26     126
    

    【讨论】:

      【解决方案3】:

      df.where + df.rank

      n = 2
      k = 3
      df.where(df.rank(1, method='dense') <= len(df.columns)-n, df*k)
      
                   c1  c2  c3   c4
      12/12/2016  114  30   1    8
      12/11/2016  132  12  17  138
      12/10/2016   39   6   2   21
      12/09/2016    9  48  13   78
      

      要解决您的更新问题,您仍然可以使用 where + rank,尽管它似乎不如上述操作适合。

      df['new_col'] = df.where(df.rank(1, method='dense') >= len(df.columns)-n, df*0).sum(1)*k
      
                  c1  c2  c3  c4  new_col
      12/12/2016  38  10   1   8      144
      12/11/2016  44  12  17  46      270
      12/10/2016  13   6   2   7       60
      12/09/2016   9  16  13  26      126
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-02
        • 1970-01-01
        • 2019-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-22
        相关资源
        最近更新 更多