[英]Subtracting a value in a column based on condition
Here is the set up of my dataframe: 这是我的数据框的设置:
import pandas as pd
a=pd.DataFrame([[101,'RK',1,'01','A',200],[101,'FET01',1,'02','B',10],
[101,'CS',1,'01','C',300],[101,'AS',1,'03','D',250],
[101,'FET02',1,'04','E',15],[102,'DG',1,'05','F',200],
[103,'GH',3,'06','G',150],[103,'FET01',3,'08','H',12]],
columns=['Inv','Item','Order','Warehouse','Module','Amt'])
Output: 输出:
Inv Item Order Warehouse Module Amt
0 101 RK 1 01 A 200
1 101 FET01 1 02 B 10
2 101 CS 1 01 C 300
3 101 AS 1 03 D 250
4 101 FET02 1 04 E 15
5 102 DG 1 05 F 200
6 103 GH 3 06 G 150
7 103 FET01 3 08 H 12
I would like to substract the Amt
of an Item
from it's corresponding FET Amt
. 我想的。减去
Amt
的的Item
,从它的相应的FET Amt
。 For eq, as Item
RK in the first row has Item
FET01 beneath it, the Amt for RK should be changed to (200-10). 对于等式,由于第一行中的
Item
RK在其下具有Item
FET01 ,因此应将RK的Amt更改为(200-10)。 In the 3rd row, Item
CS does not have FET beneath it, the Amt
should not change. 在第3行中,
Item
CS下方没有FET , Amt
不应更改。 In the fourth row, there is FET beneath Item
AS , the Amt
should be subtracted from it's FET which is (250-15). 在第四行中,在
Item
AS下方有FET ,应从其FET中减去Amt
(250-15)。
The final output should be: 最终输出应为:
Inv Item Order Warehouse Module Amt
0 101 RK 1 01 A 190
1 101 FET01 1 02 B 10
2 101 CS 1 01 C 300
3 101 AS 1 03 D 235
4 101 FET02 1 04 E 15
5 102 DG 1 05 F 200
6 103 GH 3 06 G 138
7 103 FET01 3 08 H 12
You could do 你可以做
In [1333]: check = df.Item.str.startswith('FET').shift(-1).fillna(False)
In [1334]: df.loc[check, 'Amt'] = df.Amt.diff(-1)
In [1325]: df
Out[1325]:
Inv Item Order Warehouse Module Amt
0 101 RK 1 1 A 190.0
1 101 FET01 1 2 B 10.0
2 101 CS 1 1 C 300.0
3 101 AS 1 3 D 235.0
4 101 FET02 1 4 E 15.0
5 102 DG 1 5 F 200.0
6 103 GH 3 6 G 138.0
7 103 FET01 3 8 H 12.0
Details
In [1336]: check
Out[1336]:
0 True
1 False
2 False
3 True
4 False
5 False
6 True
7 False
Name: Item, dtype: bool
You can do this by simply iterating through your dataframe, checking what is the value of 'Item' in the next row, and subtracting if it contains 'FET': 您可以通过简单地遍历数据帧,检查下一行中“ Item”的值,然后减去其中是否包含“ FET”来实现此目的:
for ii, row in a.iterrows():
if ii+1 >= len(a):
break
if 'FET' in a.iloc[ii+1]['Item']:
a.set_value( ii, 'Amt', a.iloc[ii]['Amt']-a.iloc[ii+1]['Amt'] )
print a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.