How to Use Map and Lambda Functions to Fill NaN Values in Pandas (Python)?

Estimated read time 1 min read

To fill NaN values in Pandas using map and lambda functions, you can follow these steps:

  1. Import the Pandas library.
  2. Create a Pandas DataFrame with NaN values.
  3. Use the map and lambda functions to fill NaN values with a specified value.
  4. Print the updated DataFrame.

Here is an example code snippet to fill NaN values in a Pandas DataFrame using map and lambda functions:

import pandas as pd

# Create a Pandas DataFrame with NaN values
df = pd.DataFrame({'A': [1, 2, None, 4], 'B': [None, 6, 7, 8], 'C': [9, None, 11, None]})
print('Original DataFrame:')
print(df)

# Use map and lambda functions to fill NaN values with -1
df = df.apply(lambda x: x.map(lambda y: y if pd.notnull(y) else -1))

print('\nUpdated DataFrame:')
print(df)

In the above code, we create a Pandas DataFrame with some NaN values in columns A, B, and C. Then, we use the apply method to apply the map and lambda functions to each column. The lambda function checks if the value is not null using the pd.notnull function. If the value is not null, it returns the value, else it returns -1. Finally, the apply method updates the DataFrame with the filled NaN values.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply