1

I have a pandas dataframe like this :

id  target
0   0.5595
1   0.9642
2   0.6225
3   0.1256
4   0.1966

For example, if the numbers in the target variable are greater than 0.5, I want to add 0.2 and change that number.

How can i do this ?

foxfire
  • 41
  • 5

1 Answers1

2

Here no loops are necessary, because vectorized alternatives exist.

Using DataFrame.loc is the simplest way:

df.loc[df.target.gt(0.5), 'target'] += 0.2 

Which is the same as:

df.loc[df.target.gt(0.5), 'target'] = df.loc[df.target.gt(0.5), 'target'] + 0.2 

It is also possible to use np.where:

df.target = np.where(df.target.gt(0.5), df.target + 0.2, df.target)

Btw, the not recommended for solution would be:

df.target = [x + 0.2 if x > 0.5 else x for x in df.target]
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252