1

I have a dataframe like this:

df = pd.DataFrame()
df['vals'] = [1,2,3,4,5]
df['flagged'] = ['N','Y','N','N','Y']

What is this most idiomatic way of modifying the values column, where the flag is 'Y'. For example, add 5 to each flagged value, so that df['vals'] == [1,7,3,4,10].

max
  • 3,652
  • 2
  • 21
  • 52

3 Answers3

5

Assign it back

df.loc[df.flagged.eq('Y'),'vals']+=5

df
Out[220]: 
   vals flagged
0     1       N
1     7       Y
2     3       N
3     4       N
4    10       Y
BENY
  • 296,997
  • 19
  • 147
  • 204
  • This makes sense, but for multiplication it isn't as concise - so for example is there a better way of writing this? `df.loc[df['flagged'] == 'Y', 'vals'] = df.loc[df['flagged'] == 'Y', 'vals'] * 2` – max Jul 02 '19 at 14:18
  • 1
    ·df.loc[df['flagged'] == 'Y', 'vals'] =df.vals * 2·@max , pandas is match the index as hidden key , so the same condition one need show on the right – BENY Jul 02 '19 at 14:18
  • That makes sense, thank you! – max Jul 02 '19 at 14:21
4

Try using .loc:

df.loc[df['flagged'] == 'Y', 'vals'] += 5

And now:

print(df)

Is:

   vals flagged
0     1       N
1     7       Y
2     3       N
3     4       N
4    10       Y
U12-Forward
  • 65,118
  • 12
  • 70
  • 89
1

Not the most idiomatic, but interesting

df.vals += 5 * df.flagged.eq('Y')

df

   vals flagged
0     1       N
1     7       Y
2     3       N
3     4       N
4    10       Y
piRSquared
  • 265,629
  • 48
  • 427
  • 571