import pandas as pd
import numpy as np
my_dict={'NAME':['Ravi','Raju','Alex',None,'King',None],
'ID':[1,2,np.NaN,4,5,6],
'MATH':[np.NaN,80,70,70,82,30],
'ENGLISH':[81,70,40,50,np.NaN,30]}
df = pd.DataFrame(data=my_dict)
print(df) # output without replacing
df=df.fillna('D') # output after replacing
print(df)
Output is here , both outputs are given for better comparison.
| print(df) | df=df.fillna('D') print(df) |
| |
fillna(self, value=None, method=None, axis=None,
inplace=False, limit=None, downcast=None)
Return the Modified DataFrame ( if inplace=True ).
value | Value to be replaced. Can be 0. We can use method to replace NaN data also |
method | How to use the fill, values are backfill, ffill, pad |
axis | 0 or 1 or Column, the axis to be used for replacement |
inplace | Boolean , along with method if value is True then original ( source ) dataframe is replaced after applying fillna() |
limit | Number , along with method this is the maximum number of replacements allowed. |
downcast | what to downcast if possible |
import pandas as pd
import numpy as np
my_dict={'NAME':['Ravi','Raju','Alex',None,'King',None],
'ID':[1,2,np.NaN,4,5,6],
'MATH':[np.NaN,80,70,70,82,30],
'ENGLISH':[81,70,40,50,np.NaN,30]}
df = pd.DataFrame(data=my_dict)
print(df)
df['ENGLISH']=df['ENGLISH'].fillna(method='backfill')
df['NAME']=df['NAME'].fillna(method='bfill')
df['MATH']=df['MATH'].fillna(method='pad')
df['ID']=df['ID'].fillna(method='ffill')
print(df)
my_dict={'NAME':['Ravi','Raju','Alex',None,'King',None],
'ID':[1,2,np.NaN,4,5,6],
'MATH':[np.NaN,80,70,70,82,30],
'ENGLISH':[81,70,40,50,np.NaN,30]}
df = pd.DataFrame(data=my_dict)
df=df.fillna(method='backfill',axis=1)
print(df)
Output
NAME ID MATH ENGLISH
0 Ravi 1 81 81
1 Raju 2 80 70
2 Alex 70 70 40
3 4 4 70 50
4 King 5 82 NaN
5 6 6 30 30
import pandas as pd
import numpy as np
my_dict={'NAME':['Ravi','Raju',None,None,'King',None],
'ID':[1,np.NaN,np.NaN,4,5,6],
'MATH':[np.NaN,80,70,70,82,30],
'ENGLISH':[81,70,40,np.NaN,np.NaN,30]}
df = pd.DataFrame(data=my_dict)
df=df.fillna(method='bfill',axis=0,limit=1)
print(df)
Output is here ( note that only one data is replaced in each column ) , the data which are not replaced are highlighted.
NAME ID MATH ENGLISH
0 Ravi 1.0 80.0 81.0
1 Raju NaN 80.0 70.0
2 None 4.0 70.0 40.0
3 King 4.0 70.0 NaN
4 King 5.0 82.0 30.0
5 None 6.0 30.0 30.0
df = pd.DataFrame(data=my_dict)
df.fillna('D',inplace=True)
print(df)
Output
NAME ID MATH ENGLISH
0 Ravi 1 80 81
1 Raju 2 40 70
2 Alex D 70 40
3 D 4 70 50
4 King 5 82 D
5 D 6 30 30
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.