gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
python how to handle Dataframe with value [ np.nan(), 'false', 'true'] to [-1,0,1]
- User
python how to handle Dataframe with value [ np.nan(), 'false', 'true'] to [-1,0,1]
- Assistant
You can map the values
[np.nan, 'false', 'true']in a pandas DataFrame column to[-1, 0, 1]by using a combination ofmap()andfillna()or by applying a custom function.Here is a simple example:
import pandas as pd import numpy as np # Sample dataframe df = pd.DataFrame({ 'col': [np.nan, 'false', 'true', 'true', 'false', np.nan] }) # Define a mapping dictionary mapping = { 'false': 0, 'true': 1 } # Map the values, then fill NaN with -1 df['col_mapped'] = df['col'].map(mapping).fillna(-1).astype(int) print(df)Output:
col col_mapped 0 NaN -1 1 false 0 2 true 1 3 true 1 4 false 0 5 NaN -1Explanation:
.map(mapping): converts'false'to0and'true'to1.np.nanvalues are untouched and remainNaN..fillna(-1): replacesNaNvalues with-1..astype(int): ensures the column dtype is int.
If your values are all strings and
np.nanis actual missing values (NaN), this approach is simple and efficient.