map() function inserting NaN, possible to return original values instead?

Learn why map() function inserting NaN, possible to return original values instead? By Pranit Sharma Last updated : October 06, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose we are given a Pandas dataframe and we are passing a dictionary to the map function to decode the values in the column of this dataframe. However, there are some values in the original series that are not explicitly in the dictionary and it gets recorded in the form of Nan.

map() function inserting NaN, possible to return original values instead

We need to find an easy way to return the original value instead of the NaN value. For this purpose, we will replace the original series with the new dictionary so that it will replace all the values of the dictionary with the non-null values of the series and the nan value would be retained as the original value.

Let us understand with the help of an example,

Python program to demonstrate why map() function inserting NaN, possible to return original values instead

# Importing pandas
import pandas as pd

# Import numpy
import numpy as np

# Creating a Series
s = pd.Series(['foo','loo','bar','fun'])

# Display original Series
print("Original Series:\n",s,"\n")

# Creating a dictionary
d = {'foo':'A','loo':'B','bar':'C'}

# Passing dict into map
res = s.map(d)

# Display result
print("Result:\n",res)

# Retaining all the values and 
# nan values as original value
res = s.replace(d)

# Display result
print("Result:\n",res)

Output

The output of the above program is:

Example: map() function inserting NaN, possible to return original values instead?frame

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.