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
  • 4,141
  • 5
  • 26
  • 55

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
  • 317,841
  • 20
  • 164
  • 234
  • 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
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
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
  • 285,575
  • 57
  • 475
  • 624