Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set value to a cell filtered by rows in python DataFrame?

import pandas as pd

df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9],[10,11,12]],columns=['A','B','C'])
df[df['B']%2 ==0]['C'] = 5

I am expecting this code to change the value of columns C to 5, wherever B is even. But it is not working.

It returns the table as follow

    A   B   C
0   1   2   3
1   4   5   6
2   7   8   9
3   10  11  12

I am expecting it to return

    A   B   C
0   1   2   5
1   4   5   6
2   7   8   5
3   10  11  12
like image 737
Palash Tichkule Avatar asked Aug 31 '25 22:08

Palash Tichkule


1 Answers

If need change value of column in DataFrame is necessary DataFrame.loc with condition and column name:

df.loc[df['B']%2 ==0, 'C'] = 5
print (df)
    A   B   C
0   1   2   5
1   4   5   6
2   7   8   5
3  10  11  12

Your solution is nice example of chained indexing - docs.

like image 112
jezrael Avatar answered Sep 03 '25 18:09

jezrael