将数据帧 python 中每一行的前 h 个值乘以 k

我有一个数据框,其中一些日期作为行和列中的值。要了解 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 的新列中。任何建议或提示都非常感谢!


翻过高山走不出你
浏览 164回答 3
3回答

摇曳的蔷薇

nlargestdf.assign(newcol=df.apply(sorted, 1).iloc[:, -2:].sum(1) * 3)            c1  c2  c3  c4  newcol12/12/2016  38  10   1   8     14412/11/2016  44  12  17  46     27012/10/2016  13   6   2   7      6012/09/2016   9  16  13  26     126partitiondf.assign(newcol=np.partition(df, -2)[:, -2:].sum(1) * 3)            c1  c2  c3  c4  newcol12/12/2016  38  10   1   8     14412/11/2016  44  12  17  46     27012/10/2016  13   6   2   7      6012/09/2016   9  16  13  26     126

MMTTMM

update在groupby+之后使用nlargestdf.update(df.stack().groupby(level=0).nlargest(2).mul(k).reset_index(level=0,drop=True).unstack())dfOut[1036]:                c1    c2  c3     c412/12/2016  114.0  30.0   1    8.012/11/2016  132.0  12.0  17  138.012/10/2016   39.0   6.0   2   21.012/09/2016    9.0  48.0  13   78.0

红糖糍粑

与df.where+df.rankn = 2k = 3df.where(df.rank(1, method='dense') <= len(df.columns)-n, df*k)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;c1&nbsp; c2&nbsp; c3&nbsp; &nbsp;c412/12/2016&nbsp; 114&nbsp; 30&nbsp; &nbsp;1&nbsp; &nbsp; 812/11/2016&nbsp; 132&nbsp; 12&nbsp; 17&nbsp; 13812/10/2016&nbsp; &nbsp;39&nbsp; &nbsp;6&nbsp; &nbsp;2&nbsp; &nbsp;2112/09/2016&nbsp; &nbsp; 9&nbsp; 48&nbsp; 13&nbsp; &nbsp;78为了解决您的更新,您仍然可以使用 where + rank,尽管它似乎不如上述操作适合。df['new_col'] = df.where(df.rank(1, method='dense') >= len(df.columns)-n, df*0).sum(1)*k&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c1&nbsp; c2&nbsp; c3&nbsp; c4&nbsp; new_col12/12/2016&nbsp; 38&nbsp; 10&nbsp; &nbsp;1&nbsp; &nbsp;8&nbsp; &nbsp; &nbsp; 14412/11/2016&nbsp; 44&nbsp; 12&nbsp; 17&nbsp; 46&nbsp; &nbsp; &nbsp; 27012/10/2016&nbsp; 13&nbsp; &nbsp;6&nbsp; &nbsp;2&nbsp; &nbsp;7&nbsp; &nbsp; &nbsp; &nbsp;6012/09/2016&nbsp; &nbsp;9&nbsp; 16&nbsp; 13&nbsp; 26&nbsp; &nbsp; &nbsp; 126
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python