[Python] Convert (Many) Integer-Valued Rows into a Binary Indicator Column in Pandas

Discussão em 'Python' iniciado por Stack, Agosto 4, 2025.

  1. Stack

    Stack Membro Participativo

    This seems a little to me like one-hot encoding, but notably different. What I want to do is take a row of integers from a Pandas DataFrame and produce a binary column with 1's at the index locations specified by the integers and 0's everywhere else. If possible, I would like to do this for many rows at the same time. So a trivial example would be given as taking

    A B C
    1 4 7
    2 5 8
    3 6 9

    and producing

    index .1 .2 .3
    1 1 0 0
    2 0 1 0
    3 0 0 1
    4 1 0 0
    5 0 1 0
    6 0 0 1
    7 1 0 0
    8 0 1 0
    9 0 0 1

    Is there a built in function that does something similar to this? Thanks for any help!

    Continue reading...

Compartilhe esta Página