Home > Net >  simple mapping of pandas series to 0 and 1s given threshold
simple mapping of pandas series to 0 and 1s given threshold

Time:04-03

I am sorry for asking such a simple question (yes I googled). Do I really require 2 steps to map a simple pandas series of float between 0 and 1s to 0 and 1s given a threshold. This is the reproducible example:

series = pd.Series([0.0, 0.3, 0.6, 1.0])
threshold = 0.5
print(series)

series[series > threshold] = 1.0
series[series <= threshold] = 0.0

print(series)

It works producing:

0    0.0
1    0.0
2    1.0
3    1.0

from:

0    0.0
1    0.3
2    0.6
3    1.0

CodePudding user response:

You can use the > operator.

series = (series > threshold).astype(int)
print(series)

Output:

0    0
1    0
2    1
3    1
dtype: int32

CodePudding user response:

You could also apply a function on all elements using map() like

series = series.map(lambda x: 1.0 if x > threshold else 0.0)

CodePudding user response:

I'd use numpy.where:

np.where(series > threshold, 1, 0)
  • Related