python - 熊猫:使用具有多个条件的最后一列值?
问题描述
我试图弄清楚如何使用 Y 的最后一列中的值与多个条件来导出 Z 和 P。
- 当 Y 介于 2 到 6 之间时 = 最后一列 Z + 5,
- 当 Y 为 1 时,下一列 Z = 0 + 5,
- 当 Y 介于 2 到 6 之间时,列 Q = 0,
- 当 Y 为 1 时,列 Q = X 乘以 Z
原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]}
非常感谢
解决方案
GroupBy.cumcount
由 helper使用,并使用Series
创建的移位掩码,Series.cumsum
然后添加Series.add
with1
和 multiple by 5
with Series.mul
and 以供下一列使用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
推荐阅读
- reactjs - Redux 和 Typescript 中间件
- regex - 使用 mac 终端删除文件
- mysql - 组查询不支持 mysql 8;
- sql - SQL查询“折叠”靠近在一起的行
- python - 如何为 PrimeFaces 编写 Python 硒测试?
- javascript - 通过 cors 将 base64 图像插入 MySQL 数据库的最佳方法是什么?(MySQL+Express+React+Node 栈)
- python - Python3:使用 Dateutil 从长字符串中创建多个变量
- android-room - 在 Android Room 中使用 sql 语句出错:SQL 错误或缺少数据库(没有这样的列:xx)
- laravel - 在表格列中使用带空格的 Eloquent
- shiny - 使用 shinyproxy 部署闪亮 - 没有应用程序显示