簡體   English   中英

將數據幀python中的每一行的頂部h值乘以k乘以k

[英]Multiply top h values times k for each row in a dataframe python

我有一個數據框,其中一些日期為列中的行和值。 要知道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的新列中。 任何建議或提示都非常感謝!

謝謝!

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

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

使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM