Stacey - 3 months ago 21

Python Question

I have a data frame

`dayData`

`'ratio'`

`'first_power'`

`Name: ratio, dtype: float64 first power`

Name: first_power, dtype: object average power

ratio average_power

0 5 8.0

1 6 4.0

2 7 0.0

3 0 6.0

4 8 5.0

5 9 4.0

6 8 2.0

7 7 8.0

8 6 0.0

9 5 5.0

10 8 4.0

The next stage in my process is to create a second step power by dividing the 2 columns using the following formula:

`dayData["second_step_power"] = np.where(dayData.average_power == 0.0, 0, dayData.first_power/dayData.average_power)`

Obviously you can't divide by zero so in the event the average_power is zero I am trying to set the second_step_power to be 0, however I get the error:

`ZeroDivisionError: float division by zero`

Could someone let me know the correct way of handling zeros so the code

My ideal output would be:

`ratio average_power second_step_power`

0 5 8.0 0.625

1 6 4.0 1.500

2 7 0.0 0.000

3 0 6.0 0.000

4 8 5.0 1.600

5 9 4.0 2.250

6 8 2.0 4.000

7 7 8.0 0.875

8 6 0.0 0.000

9 5 5.0 1.000

10 8 4.0 2.000

Thanks

Answer

You can initially set all values to zero, then create a mask locating all rows with a valid denominator, i.e. where `power`

is greater than zero (`gt(0)`

). Finally, use the mask together with `loc`

to calculate `second_step_power`

.

```
df['second_step_power'] = 0
mask = df.average_power.gt(0)
df.loc[mask, 'second_step_power'] = \
df.loc[mask, 'first_power'] / df.loc[mask, 'average_power']
```

Source (Stackoverflow)

Comments