Weth Will Weth Will - 5 months ago 9
Python Question

Two Pandas Series replacement values using intermediate one

I'am new to Pandas, trying to use three Series like this ...

First one X :

DATE
2015-10-10 00:00:00 0.0
2015-10-10 01:00:00 290.0
2015-10-10 02:00:00 225.0
2015-10-10 03:00:00 4.0
2015-10-10 04:00:00 2.0
Name: X, dtype: bool


Second one S :

DATE
2015-10-10 00:00:00 True
2015-10-10 01:00:00 False
2015-10-10 02:00:00 False
2015-10-10 03:00:00 True
2015-10-10 04:00:00 True
Name: S, dtype: bool


Third one Average :

DATE
2015-10-10 00:00:00 0.000000
2015-10-10 01:00:00 145.000000
2015-10-10 02:00:00 171.666667
2015-10-10 03:00:00 128.750000
2015-10-10 04:00:00 103.000000
Name: average, dtype: bool


What I want to do is :
replace values in X with the corresponding values by index in Average if it is True in S.
What is the best and more efficient way to do that ?

Answer

You can use where passing in the Series to test against:

In [231]:
Average.where(S==True, X)

Out[231]:
DATE
2015-10-10 00:00:00      0.00
2015-10-10 01:00:00    290.00
2015-10-10 02:00:00    225.00
2015-10-10 03:00:00    128.75
2015-10-10 04:00:00    103.00
Name: val, dtype: float64