Bradypodion
Bradypodion

Reputation: 81

Pandas: change value of a cell based on a condition

STRINGS      NUMBER         
hello        10
byebye       9
hello        20
hello        21

Stucked on this:

Changing the value of NUMBER cells when its value is greater than 10 and 'hello' in STRINGS is at the same index.

I tried:

df.loc[df['STRING'] == 'hello' > 10, 'NUMBER'] = 100

or

df.loc[x.STRING.str.contains('hello') > 10, 'NUMBER'] = 100

The results should be this:

 STRINGS      NUMBER
  hello        10
  byebye       9
  hello        100
  hello        100

Any advice? Thanks!

Upvotes: 2

Views: 1226

Answers (2)

Nk03
Nk03

Reputation: 14949

via np.where:

df['NUMBER'] = np.where((df['STRINGS'] == 'hello') & (df['NUMBER'] > 10), 100, df['NUMBER'])

Upvotes: 1

jezrael
jezrael

Reputation: 863166

You need chain both conditions with () and & for bitwise AND:

df.loc[(df['STRING'] == 'hello') & (df['NUMBER'] > 10), 'NUMBER'] = 100

Upvotes: 3

Related Questions