Update elements of dataframe by applying function involving same row elements
You can use reshape columns i
and j
and subtract,
df = df.iloc[:, :8].sub(df['i'].values[:, None]).div(df['j'].values[:, None]).round(2)
a b c d e f g h
0 8.18 17.27 26.36 35.45 44.55 53.64 62.73 71.82
1 90.00 98.33 106.67 115.00 123.33 131.67 140.00 148.33
2 159.23 166.92 174.62 182.31 190.00 197.69 205.38 213.08
3 218.57 225.71 232.86 240.00 247.14 254.29 261.43 268.57
Make use of filter
and the underlying numpy
arrays.
u = df.filter(regex='[^ij]')
res = (u.values - df.i.values[:, None]) / df.j.values[:, None]
pd.DataFrame(res, columns=u.columns)
a b c d e f g h
0 8.181818 17.272727 26.363636 35.454545 44.545455 53.636364 62.727273 71.818182
1 90.000000 98.333333 106.666667 115.000000 123.333333 131.666667 140.000000 148.333333
2 159.230769 166.923077 174.615385 182.307692 190.000000 197.692308 205.384615 213.076923
3 218.571429 225.714286 232.857143 240.000000 247.142857 254.285714 261.428571 268.571429
Try using sub
and div
with index slicing:
df.loc[:, 'a':'h'] = df.loc[:, 'a':'h'].sub(df['i'], axis=0).div(df['j'], axis=0)
Output:
a b c d e f \
0 8.181818 17.272727 26.363636 35.454545 44.545455 53.636364
1 90.000000 98.333333 106.666667 115.000000 123.333333 131.666667
2 159.230769 166.923077 174.615385 182.307692 190.000000 197.692308
3 218.571429 225.714286 232.857143 240.000000 247.142857 254.285714
g h i j
0 62.727273 71.818182 0.1 0.11
1 140.000000 148.333333 0.2 0.12
2 205.384615 213.076923 0.3 0.13
3 261.428571 268.571429 0.4 0.14