首页 > 解决方案 > 熊猫:使用具有多个条件的最后一列值?

问题描述

我试图弄清楚如何使用 Y 的最后一列中的值与多个条件来导出 Z 和 P。

原DF:

╔════╦═══╗
║ X ║ Y ║
╠════╬═══╣
║ 29 ║ 5 ║
║ 28 ║ 4 ║
║ 32 ║ 3 ║
║ 29 ║ 3 ║
║ 26 ║ 1 ║
║ 38 ║ 5 ║
║ 25 ║ 2 ║
║ 33 ║ 3 ║
║ 25 ║ 3 ║
║ 25 ║ 5 ║
║ 40 ║ 1 ║
║ 30 ║ 6 ║
║ 31 ║ 3 ║
║ 38 ║ 5 ║
╚════╩═══╝

需要的输出:

╔════╦═══╦═════╦══════╗
║ X ║ Y ║ Z ║ P ║
╠════╬═══╬═════╬══════╣
║ 29 ║ 5 ║ 5 ║ 0 ║
║ 28 ║ 4 ║ 10 ║ 0 ║
║ 32 ║ 3 ║ 15 ║ 0 ║
║ 29 ║ 3 ║ 20 ║ 0 ║
║ 26 ║ 1 ║ 25 ║ 650 ║
║ 38 ║ 5 ║ 5 ║ 0 ║
║ 25 ║ 2 ║ 10 ║ 0 ║
║ 33 ║ 3 ║ 15 ║ 0 ║
║ 25 ║ 3 ║ 20 ║ 0 ║
║ 25 ║ 5 ║ 25 ║ 0 ║
║ 40 ║ 1 ║ 30 ║ 1200 ║
║ 30 ║ 6 ║ 5 ║ 0 ║
║ 31 ║ 3 ║ 10 ║ 0 ║
║ 38 ║ 5 ║ 15 ║ 0 ║
╚════╩═══╩═════╩══════╝

我做了一些研究,发现使用了 shift ,但是,我不知道如何添加其他条件

data = {'X':[29,28,32,29,26,38,25,33,25,25,40,30,31,38], 'Y':[5,4,3,3,1,5,2,3,3,5,1,6,3,5]}

非常感谢

标签: pythonpandas

解决方案


GroupBy.cumcount由 helper使用,并使用Series创建的移位掩码,Series.cumsum然后添加Series.addwith1和 multiple by 5with Series.muland 以供下一列使用numpy.where

m = df['Y'].eq(1)
df['Z'] = df.groupby(m.shift().bfill().cumsum()).cumcount().add(1).mul(5)
df['P'] = np.where(m, df.X.mul(df.Z), 0)
print (df)
     X  Y   Z     P
0   29  5   5     0
1   28  4  10     0
2   32  3  15     0
3   29  3  20     0
4   26  1  25   650
5   38  5   5     0
6   25  2  10     0
7   33  3  15     0
8   25  3  20     0
9   25  5  25     0
10  40  1  30  1200
11  30  6   5     0
12  31  3  10     0
13  38  5  15     0

推荐阅读