0

I trying to write a script that will multiply the value in a in a row of a pandas if a specific value exists in the corresponding row of another column.

I'm using a for loop and "if in" statement but it is not recognizing that the variable exists in the first column at all, let alone applying the multiplication.

Here is some example code:

import pandas as pd

data = {'Person': ['Jim', 'Jim', 'Jim', 'Jim', 'Jim', 'Bob','Bob','Bob','Bob','Bob',], 
'Result': ['Good', 'Good','Good','Good','Good','Good','Bad','Good','Bad','Bad',],
'Value':[1,2,3,1,2,3,1,2,1,4]}
df = pd.DataFrame.from_dict(data)

for i in df['Result']:
    if 'Bad' in df['Result']:
        print(i)
        df['Value'] * 2

The current result is:

Person     Result   Value
0    Jim   Good      1
1    Jim   Good      2
2    Jim   Good      3
3    Jim   Good      1
4    Jim   Good      2
5    Bob   Good      3
6    Bob    Bad      1
7    Bob   Good      2
8    Bob    Bad      1
9    Bob    Bad      4

What I'm trying to achieve is:

Person     Result   Value
0    Jim   Good      1
1    Jim   Good      2
2    Jim   Good      3
3    Jim   Good      1
4    Jim   Good      2
5    Bob   Good      3
6    Bob    Bad      2
7    Bob   Good      2
8    Bob    Bad      2
9    Bob    Bad      8
John Conor
  • 722
  • 6
  • 20

1 Answers1

1

Use loc access:

df.loc[df['Result']=='Bad', 'Value'] *= 2
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
  • This is good, though for some reason the multiplication is returning the values multiplied by 1000... "Bad" values are 1024, 1024, 4096 instead of just *2. Are you seeing this?? – John Conor May 13 '21 at 19:20
  • Never mind... I still had it in the for loop *facepalm* – John Conor May 13 '21 at 19:32