Increase value of several rows based on condition fulfilling all rows

Viewed 376

I have a pandas dataframe with three columns and want to multiply/increase the float numbers of each row by the same amount until the sum of all three cells (one row) fulfils the critera (value equal or greater than 0.9)

df = pd.DataFrame({'A':[0.03, 0.0, 0.4],
               'B': [0.1234, 0.4, 0.333],
               'C': [0.5, 0.4, 0.0333]})

Outcome: The different cells in each row were multiplied so that the sum of all three cells of each row is 0.9 (The sum of each row is not exactly 0.9 as I tried to come close with simple multiplication, hence the actual outcome would get to 0.9). It is important that the cells which are 0 would stay 0.

print (df)
A         B         C
0  0.0414  0.170292  0.690000
1  0.0000  0.452000  0.452000
2  0.4720  0.392940  0.039294
2 Answers

You can take sum on axis=1 and subtract with 0.9 ,then divide with df.shape[1] to add it back:

df.add((0.9-df.sum(axis=1))/df.shape[1],axis=0)

         A         B         C
0  0.112200  0.205600  0.582200
1  0.033333  0.433333  0.433333
2  0.444567  0.377567  0.077867

You want to apply a scaling function along the rows:

def scale(xs, target=0.9):
    """Scale the features such that their sum equals the target."""
    xs_sum = xs.sum()
    if xs_sum < target:
        return xs * (target / xs_sum)
    else:
        return xs

df.apply(scale), axis=1)

For example:

df = pd.DataFrame({'A':[0.03, 0.0, 0.4],
                   'B': [0.1234, 0.4, 0.333],
                   'C': [0.5, 0.4, 0.0333]})
df.apply(scale, axis=1)

Should give:

          A         B         C
0  0.041322  0.169972  0.688705
1  0.000000  0.450000  0.450000
2  0.469790  0.391100  0.039110

The rows of that dataframe all sum to 0.9:

df.apply(scale), axis=1).sum(axis=1)

0    0.9
1    0.9
2    0.9
dtype: float64
Related