0

I have this dataframe

import pandas as pd
x = pd.DataFrame.from_dict({'A':[1,2,0,4,0,6], 'B':[0, 0, 0, 44, 48, 81], 'C':[1,0,1,0,1,0]})

I try to change it like this, but it doesn't work

x[x['A']>3]['A'] = 33 # has no effect

I also tried

x.loc(x['A']>3)['A'] = 33 # getting an error

So what's the right way to do this?

Baron Yugovich
  • 3,843
  • 12
  • 48
  • 76
  • 1
    Use `x.loc[x['A'].gt(3), 'A'] = 33` – user3483203 Jul 18 '18 at 16:46
  • To answer OP's question, ````x[x['A']>3]['A'] = 33```` does not modify the dataframe inplace; rather it is making a copy of a slice of the dataframe and modifying the copy. Use ````.loc```` and have your indices (row and column) within the same square bracket to modify the dataframe itself. – xyzjayne Jul 18 '18 at 16:55

1 Answers1

0

You should using .loc

x.loc[x['A']>3,'A'] = 33
x
Out[480]: 
    A   B  C
0   1   0  1
1   2   0  0
2   0   0  1
3  33  44  0
4   0  48  1
5  33  81  0

Or mask

x.A=x.mask(x.A>3,33)
x
Out[483]: 
    A   B  C
0   1   0  1
1   2   0  0
2   0   0  1
3  33  44  0
4   0  48  1
5  33  81  0
BENY
  • 317,841
  • 20
  • 164
  • 234