import pandas as pd
my_dict={'NAME':['Ravi','Raju','Alex','Ron','King','Jack'],
'ID':[1,2,3,4,5,6],
'MATH':[80,40,70,70,82,30],
'ENGLISH':[81,70,40,50,60,30]}
my_data = pd.DataFrame(data=my_dict)
my_data=my_data.mask(my_data['MATH'] > 80,-5)
print(my_data)
Output
NAME ID MATH ENGLISH
0 Ravi 1 80 81
1 Raju 2 40 70
2 Alex 3 70 40
3 Ron 4 70 50
4 -5 -5 -5 -5
5 Jack 6 30 30
You can check that the all data of 4th row is replaced by -5.my_data['MATH']=my_data['MATH'].mask(my_data['MATH'] > 80,-5)
print(my_data)
Output
NAME ID MATH ENGLISH
0 Ravi 1 80 81
1 Raju 2 40 70
2 Alex 3 70 40
3 Ron 4 70 50
4 King 5 -5 60
5 Jack 6 30 30
import pandas as pd
my_dict={'NAME':['Ravi','Raju','Alex','Ron','King','Jack'],
'ID':[1,2,3,4,5,6],
'MATH':[80,40,73,70,82,30],
'ENGLISH':[81,70,40,50,60,30]}
my_data = pd.DataFrame(data=my_dict)
my_cond= (my_data['MATH'] >70) & (my_data['MATH'] <75)
replace=-7
my_data['MATH'].mask(my_cond,replace,inplace=True)
print(my_data)
Output
NAME ID MATH ENGLISH
0 Ravi 1 80 81
1 Raju 2 40 70
2 Alex 3 -7 40
3 Ron 4 70 50
4 King 5 82 60
5 Jack 6 30 30
my_data['MATH'].mask(my_data['MATH'] > 80,-5,inplace=True)
Output: Now the original DataFrame will change.
NAME ID MATH ENGLISH
0 Ravi 1 80 81
1 Raju 2 40 70
2 Alex 3 70 40
3 Ron 4 70 50
4 King 5 -5 60
5 Jack 6 30 30
Replace data based multiple condition like CASE THEN ( SQL ) by using np.where Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.