+3 votes
in Programming Languages by (77.2k points)

I want to change the value of all rows in a column of Pandas DataFrame if a certain condition is met. 

E.g. In the following DataFrame, If the value of any row in column A is < 0.10, set it to 0.

How can I do it?

      A  B

0  0.10  0

1  0.40  1

2  0.55  1

3  0.60  1

4  0.01  0

5  1.00  0

6  1.00  0

7  0.01  1

8  0.44  0

9  0.33  1

1 Answer

+1 vote
by (354k points)
selected by
 
Best answer

You can use the following code to change the value of all rows in a column of a Pandas DataFrame. It uses .loc[] to access rows and columns of a DataFrame.

>>> y
array([0, 1, 1, 1, 0, 0, 0, 1, 0, 1])
>>> prob
array([0.1 , 0.4 , 0.55, 0.6 , 0.  , 1.  , 1.  , 0.  , 0.44, 0.33])
>>> df = pd.DataFrame({'e': prob, 'o': y})
>>> df
      e  o
0  0.10  0
1  0.40  1
2  0.55  1
3  0.60  1
4  0.00  0
5  1.00  0
6  1.00  0
7  0.00  1
8  0.44  0
9  0.33  1
>>> df.loc[df['e'] <= 0.1, 'e'] = 0
>>> df
      e  o
0  0.00  0
1  0.40  1
2  0.55  1
3  0.60  1
4  0.00  0
5  1.00  0
6  1.00  0
7  0.00  1
8  0.44  0
9  0.33  1


...