Sometimes the dataframe contains an empty column and may pose a real problem in the real life scenario. Missing Data can also refer to as NA(Not Available) values in pandas. In DataFrame sometimes many datasets simply arrive with missing data, either because it exists and was not collected or it never existed. In this article, let’s see how to fill empty columns in dataframe using pandas.
Note: Link of csv file here.
Fill empty column:
import pandas as pd
df = pd.read_csv( "Persons.csv" )
df |
First, we import pandas after that we load our CSV file in the df variable. Just try to run this in jupyter notebook or colab.
Output:
df.set_index( 'Name ' , inplace = True )
df |
This line used to remove index value, we don’t want that, so we remove it.
Output:
There are several methods used to fill the empty columns.we going to saw it one by one
Method 1:
In this method, we will use “df.fillna(0)” which replace all NaN elements with 0s.
Example:
df1 = df.fillna( 0 )
df1 |
Output:
Method 2:
In this method, we will use “df.fillna(method=’ffill’)” , which is used to propagate non-null values forward or backward.
Syntax: DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None)
df2 = df.fillna(method = 'ffill' )
df2 |
Output:
Method 3:
In this method we will use “df.interpolate()”
Syntax: DataFrame.interpolate(method=’linear’, axis=0, limit=None, inplace=False, limit_direction=None, limit_area=None, downcast=None, **kwargs)
df3 = df.interpolate()
df3 |
Output: