Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

I got an error of

TypeError: ‘float’ object is not iterable

Thanks for your help

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading