Search code examples
pythondataframedummy-variable

Convert values to dummies on threshold in dataframe or specific column


I would like to reproduce this exact code below in a one liner or with a pandas built-in function:

You have a dataframe with N columns of values where you would like assign 1 for positive and 0 for negative values

mask_dummies_1 = df > 0    # Create a mask for positive values
mask_dummies_0 = df < 0    # Create a mask for negative values
df[mask_dummies_1] = 1     # apply positive mask and take the value 1
df[mask_dummies_0] = 0     # apply positive mask and take the value 0

I know that's a dirty one ^^' Any guess ?


Solution

  • Solutions, one liner, explicit:

    df = 1 * (df > 0)
    

    for one column:

    df['col'] = 1 * (df['col'] > 0)