how to replace values in all column with condition?

Viewed 36

The searched result is all about one column, my question is how to replace values in all column when its vale meet a certain condtion

for example

df=
1 20 30
1 4 5
5 8 10

now if the value is larger than 10, replace value to be 10

so my expected result is

df=
1 10 10
1 4 5
5 8 10

the one I am thinking to do is like this:

mask=df>10
df.loc[mask]=10

I got an error of

TypeError: 'float' object is not iterable

Thanks for your help

1 Answers

Use DataFrame.clip if need replace to same value:

df = df.clip(upper=10)
print (df)
   0   1   2
0  1  10  10
1  1   4   5
2  5   8  10

Your solution should be changed:

df[df>10]=10
print (df)
   0   1   2
0  1  10  10
1  1   4   5
2  5   8  10

Or with DataFrame.mask:

df = df.mask(df > 10, 10)
print (df)
   0   1   2
0  1  10  10
1  1   4   5
2  5   8  10
Related