How to remap values in Pandas column using a dictionary, while also preserving any NaN values that may be present?

I am trying to remap values in a specific column of a Pandas DataFrame using a dictionary, while ensuring that any NaN values in the column are preserved and not modified. I am looking for alternative ways to achieve this using Pandas, and would appreciate any suggestions from the community.

To provide some context, let’s say we have a DataFrame with a column of categorical data that we want to remap. We may have a dictionary with the original values as keys and the new values as values, and want to apply this mapping to the DataFrame.

For example, suppose we have a DataFrame with a column ‘Fruit’ that contains values ‘Apple’, ‘Orange’, ‘Banana’, and ‘NaN’. We want to remap ‘Apple’ to ‘Red Apple’, ‘Orange’ to ‘Orange Fruit’, and ‘Banana’ to ‘Yellow Fruit’, while keeping any NaN values in the column unchanged. One way to achieve this is to use the map() method of the DataFrame column, combined with the fillna() method to preserve any NaN values. Here is an example code snippet that demonstrates this approach:

import pandas as pd
import numpy as np

# Create a sample DataFrame
df = pd.DataFrame({'Fruit': ['Apple', 'Orange', 'Banana', np.nan, 'Apple']})

# Define a dictionary to remap values
remap_dict = {'Apple': 'Red Apple', 'Orange': 'Orange Fruit', 'Banana': 'Yellow Fruit'}

# Apply the mapping to the column using map(), and preserve NaN values using fillna()
df['Fruit'] = df['Fruit'].map(remap_dict).fillna(df['Fruit'])


This code applies the mapping defined in remap_dict to the ‘Fruit’ column of the DataFrame using map() , and then fills any NaN values using fillna() . The resulting DataFrame will have the original values replaced with the new values defined in the dictionary, while any NaN values remain unchanged.