问题
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, choicelist)
Now lets add:
y=pd.Series(x)
Lets now use y
instead of x
. Now we need to get same result (same content as a
has, and it should be Series.) with pandas only, and the conditions and choices should be coded as above (use above code for coding conditions and choices). How to do that?
回答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
来源:https://stackoverflow.com/questions/61091827/do-what-np-selectcondlist-choicelist-does-but-instead-with-pandas-only