In this article, we will see how to convert the pandas dataframe to the dictionary by excluding Na.

to_dict() with omit parameter

The easiest way to convert a pandas data frame to a dictionary without Na values is to use the to_dict() method by omitting the na parameter. We can omit the na by setting the parameter omit. This will exclude all the Na values from the resultant dictionary.

Following is the example:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3, None], 'B': [4, None, 6, 7]})
dict_without_nan = df.to_dict('records', na='omit')
print(dict_without_nan)

In the above example, we create a pandas dataframe df with two columns A and B. Column A has a NaN value in the third row, and column B has a NaN value in the second row. We then use the to_dict() method with the na parameter set to 'omit' to convert the dataframe to a dictionary without any NaN values.

fillna()

We can also convert the pandas dataframe to a dictionary without NaN values by using the fillna(). With the fillna(), we can replace all the NaN values with a specified value before using the to_dict() method. Maybe we can replace them with an empty string before converting the dataframe to a dictionary.

Following is the example using the fillna

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3, None], 'B': [4, None, 6, 7]})
df = df.fillna('')
dict_without_nan = df.to_dict('records')
print(dict_without_nan)

Categorized in:

Tagged in: