roudan
roudan

Reputation: 4208

how to replace values in all column with condition?

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

Upvotes: 1

Views: 68

Answers (1)

jezrael
jezrael

Reputation: 862901

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

Upvotes: 3

Related Questions