根据其他三列中类别级别值的条件,使用大熊猫填充第四列
假设我们有一个数据框,DF具有四个变量,如下所示。变量d中的值基于变量a,b和C中的值。对于a的每个类别级别,变量d以a a 400开始,如果b中的值为“ no”,则A中的值降低,否则保持与以前的值相同。
df
Index A B C D
1 1 5 YES 400
2 1 5 YES 400
3 1 5 NO 395
4 1 5 NO 390
5 1 5 NO 385
6 2 5 NO 395
7 2 5 YES 395
8 2 5 YES 395
9 2 5 NO 390
10 2 5 YES 390
11 3 5 NO 395
12 3 5 NO 390
13 3 5 NO 385
14 3 5 NO 380
15 3 5 YES 380
下面给出了用于填充变量D的公式:
D1 = 400
D2 = D1=400
D3 = 400-B3
D4 = D3-B4
D5 = D4-B5
D6 = 400-B6
D7 = D6
D8 = D7
D9 = D8-B9
D10 = D9
D11 = 400-B11
D12 = D11-B12
D13 = D12-B13
D14 = D13-B14
D15 = D14
我尝试了什么?
我尝试使用pd.groupby()
和cumsum()
函数,但是在B中使用值是困难的部分。
Lets say we have a dataframe, df with four variables as given below. Value in variable D is based on values in variable A, B, and C. For every category level in A, Variable D starts with a value 400 and is reduced by the value in A if the value in B is "NO", else remains same as the previous value.
df
Index A B C D
1 1 5 YES 400
2 1 5 YES 400
3 1 5 NO 395
4 1 5 NO 390
5 1 5 NO 385
6 2 5 NO 395
7 2 5 YES 395
8 2 5 YES 395
9 2 5 NO 390
10 2 5 YES 390
11 3 5 NO 395
12 3 5 NO 390
13 3 5 NO 385
14 3 5 NO 380
15 3 5 YES 380
The formulas for filling variable D is given below:
D1 = 400
D2 = D1=400
D3 = 400-B3
D4 = D3-B4
D5 = D4-B5
D6 = 400-B6
D7 = D6
D8 = D7
D9 = D8-B9
D10 = D9
D11 = 400-B11
D12 = D11-B12
D13 = D12-B13
D14 = D13-B14
D15 = D14
What I have tried?
I have tried using pd.groupby()
and cumsum()
function but working with values in B is the difficult part.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决方案
掩码
列中的值b
其中列中的相应行c!='no'
,然后按a将屏蔽列分组
和计算cumsum
然后从400
中减去此累积总和以获取结果结果
Solution
mask
the values in columnB
where corresponding row in columnC != 'NO'
, then group the masked column byA
and calculatecumsum
then subtract this cumulative sum from400
to get the resultResult