1

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?

gabboshow
  • 5,359
  • 12
  • 48
  • 98

2 Answers2

1

In my opinion here is best/fast cast boolean mask to integers:

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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0
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
Rakesh
  • 81,458
  • 17
  • 76
  • 113