Page 77 - IPP-12-2024
P. 77
5 Sohit 96
2 Deepak 92
Program 8: Write a program to replace all negative values in a data frame with a 0.
Solution:
import pandas as pd
dic = {'Data1':[-5,-2,5,8,9,-6],
'Data2':[2,4,10,15,-5,-8]}
df=pd.DataFrame(dic)
print(df)
print()
print("DataFrame after replacing negative values with 0:::")
df[df<0]=0
print(df)
Output:
Data1 Data2
0 -5 2
1 -2 4
2 5 10
3 8 15
4 9 -5
5 -6 -8
DataFrame after replacing negative values with 0:::
Data1 Data2
0 0 2
1 0 4
2 5 10
3 8 15
4 9 0
5 0 0
Program 9: Write a program to replace all missing values in a data frame with a 999.
Solution:
import pandas as pd
import numpy as np
empdata={'empid':[101,102,103,104,105,106],
'ename':['Sachin','Vinod','Lakhbir',np.NaN,'Devinder','UmaSelvi'],
'Doj':['12-01-2012','15-01-2012','05-09-2007','17-01-
2012',np.NaN,'16-01-2012']}
df=pd.DataFrame(empdata)
print(df)
df=df.fillna({'ename':999,'Doj':999})
print()
print(df)
Output:
empid ename Doj
0 101 Sachin 12-01-2012