[Python] Calculate pairwise difference from specific columns in a dataframe

Discussão em 'Python' iniciado por Stack, Março 25, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following dataframe where I show how many times I have seen a move from Item1 to Item 2. For example there is one transition from A to B, 2 from A to C , 1 from C to A


    Item1 Item2 Moves
    1 A B 1
    2 A C 2
    3 B D 3
    4 C A 1
    5 C B 5
    6 D B 4
    7 D C 1


    I would like to calculate the difference between two items, so a newly constructed Dataframe would be the following

    Item1 Item2 Moves
    1 A B 1
    2 A C 1
    3 B D -1
    4 C B 5
    5 D C 1


    Does anyone have any idea how to do that using Pandas? I guess i need to index on the first two columns but I quite new in Pandas and i face a lot of difficulties. Thanks

    EDIT There can't be any duplicate pairs.For example you cant see twice a->b (but you can of course see b->a)

    Continue reading...

Compartilhe esta Página