Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all value in all columns in a Pandas dataframe with condition

Tags:

python

pandas

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 to replace all values that is less than 1 with 0. Yielding:

       0     1
qux  0     4.10
foo  0     0
bar  1.0   0

How can I achieve that?

like image 470
pdubois Avatar asked Jan 09 '15 09:01

pdubois


People also ask

How do you replace values in a column in a DataFrame in Python?

In order to replace a value in Pandas DataFrame, use the replace() method with the column the from and to values.


1 Answers

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 < 1
Out[156]:
         0      1
bar  False   True
foo   True   True
qux   True  False

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

like image 117
EdChum Avatar answered Oct 19 '22 10:10

EdChum