Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

python how to handle Dataframe with value [ np.nan(), 'false', 'true'] to [-1,0,1]

  1. User

    python how to handle Dataframe with value [ np.nan(), 'false', 'true'] to [-1,0,1]

  2. Assistant

    You can map the values [np.nan, 'false', 'true'] in a pandas DataFrame column to [-1, 0, 1] by using a combination of map() and fillna() 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          -1
    

    Explanation:

    • .map(mapping): converts 'false' to 0 and 'true' to 1. np.nan values are untouched and remain NaN.
    • .fillna(-1): replaces NaN values with -1.
    • .astype(int): ensures the column dtype is int.

    If your values are all strings and np.nan is actual missing values (NaN), this approach is simple and efficient.