Skip to content Skip to sidebar Skip to footer

How To Replace All Value In All Columns In A Pandas Dataframe With 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, or

Solution 1:

Use boolean 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

Just to show what is happening here performing df < 1 will return a boolean index:

In [156]:
df <1Out[156]:
         01
bar  FalseTrue
foo   TrueTrue
qux   TrueFalse

This we then pass to df as a mask and can then assign the new values as df[df<1] see the docs for further examples

Post a Comment for "How To Replace All Value In All Columns In A Pandas Dataframe With Condition"