Skip to content Skip to sidebar Skip to footer

Do What Np.select(condlist, Choicelist) Does But Instead With Pandas Only

I have code and it works fine: import numpy as np import pandas as pd x = np.arange(10) condlist = [x<3, x==5, x>5] choicelist = [x, x**2, x**3] a=np.select(condlist, choic

Solution 1:

construct a dataframe from choicelist and use df.where with condlist

s = pd.DataFrame(choicelist).where(condlist).ffill().fillna(0).iloc[-1]

Out[99]:
0      0.0
1      1.0
2      2.0
3      0.0
4      0.0
5     25.0
6    216.0
7    343.0
8    512.0
9    729.0
Name: 2, dtype: float64

If conditions are not overlapped, you may also use sum

s = pd.DataFrame(choicelist).where(condlist,0).sum()

Out[114]:
0      0
1      1
2      2
3      0
4      0
5     25
6    216
7    343
8    512
9    729
dtype: int64

Post a Comment for "Do What Np.select(condlist, Choicelist) Does But Instead With Pandas Only"