[Python] Create new column based on category column [duplicate]

Discussão em 'Python' iniciado por Stack, Maio 30, 2025.

  1. Stack

    Stack Membro Participativo

    I have a dataframe that contains a column which is a categorical variable like so:

    df = pd.DataFrame({'category': ['A', 'C', 'B', 'B', 'A', 'D']})


    I wish to create a columnn for each category where if it is a member of the category it has a 1 and otherwise a 0.

    I am currently doing this like so for each category:

    df['A'] = np.where(df['category']=='A', 1,0)
    df['B'] = np.where(df['category']=='B', 1,0)
    ...


    This works, but is there a better/more efficient way to do this?

    Continue reading...

Compartilhe esta Página