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
. For eq, as Item
RK in the first row has Item
FET01 beneath it, the Amt for RK should be changed to (200-10). In the 3rd row, Item
CS does not have FET beneath it, the Amt
should not change. In the fourth row, there is FET beneath Item
AS , the Amt
should be subtracted from it's FET which is (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':
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.