How to replace all values ​​in all columns in a Pandas data frame with a condition

I have the following data frame:

In [11]: import pandas as pd In [12]: mydict = {'foo':[0, 0.3], 'bar':[1,0.55], 'qux': [0.3,4.1]} In [13]: df = pd.DataFrame.from_dict(mydict, orient='index') In [14]: df Out[14]: 0 1 qux 0.3 4.10 foo 0.0 0.30 bar 1.0 0.55 

What I want to do is replace all values ​​that are less than 1 with 0. Conceding:

  0 1 qux 0 4.10 foo 0 0 bar 1.0 0 

How can i achieve this?

+6
source share
1 answer

Use logical indexing and pass the condition:

 In [155]: df[df<1] = 0 df Out[155]: 0 1 bar 1 0.0 foo 0 0.0 qux 0 4.1 

To show what happens here, executing df < 1 will return a logical index:

 In [156]: df < 1 Out[156]: 0 1 bar False True foo True True qux True False 

Then we go to df as a mask and then we can assign new values ​​as df[df<1] see docs for other examples

+6
source

Source: https://habr.com/ru/post/980751/


All Articles