I have below data frame:
JavaScript
x
12
12
1
a
2
100
3
200
4
200
5
b
6
20
7
30
8
40
9
c
10
400
11
50
12
Need help to calculate sum of values for each item and place it in 2nd column, which ideally should look like below:
JavaScript
1
12
12
1
a 500
2
100
3
200
4
200
5
b 90
6
20
7
30
8
40
9
c 450
10
400
11
50
12
Advertisement
Answer
If need sum by groups by column col
converted to numeric use GroupBy.transform
with repeated non numeric values by ffill
:
JavaScript
1
17
17
1
s = pd.to_numeric(df['col'], errors='coerce')
2
mask = s.isna()
3
df.loc[mask, 'new'] = s.groupby(df['col'].where(mask).ffill()).transform('sum')
4
print (df)
5
col new
6
0 a 500.0
7
1 100 NaN
8
2 200 NaN
9
3 200 NaN
10
4 b 90.0
11
5 20 NaN
12
6 30 NaN
13
7 40 NaN
14
8 c 450.0
15
9 400 NaN
16
10 50 NaN
17
Or:
JavaScript
1
15
15
1
df['new'] = np.where(mask, new.astype(int), '')
2
print (df)
3
col new
4
0 a 500
5
1 100
6
2 200
7
3 200
8
4 b 90
9
5 20
10
6 30
11
7 40
12
8 c 450
13
9 400
14
10 50
15