I have a pandas series and I would like to replace the values with 0 if the value < 3 and with 1 if the value >=3
se = pandas.Series([1,2,3,4,5,6])
se[se<3]=0
se[se>=3]=1
Is there a better/pythonic way to do so?
I have a pandas series and I would like to replace the values with 0 if the value < 3 and with 1 if the value >=3
se = pandas.Series([1,2,3,4,5,6])
se[se<3]=0
se[se>=3]=1
Is there a better/pythonic way to do so?
In my opinion here is best/fast cast boolean mask to integer
s:
se = (se >= 3).astype(int)
Or use numpy.where
, but Series
constructor is necessary, because returned numpy array:
se = pd.Series(np.where(se < 3, 0, 1), index=se.index)
print (se)
0 0
1 0
2 1
3 1
4 1
5 1
dtype: int32
import pandas
se = pandas.Series([1,2,3,4,5,6])
print(se.apply(lambda x: 1 if x >=3 else 0))
Output:
0 0
1 0
2 1
3 1
4 1
5 1
dtype: int64