[Python] Sorting a dataframe column using a list with repeated values

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

  1. Stack

    Stack Membro Participativo

    Given a dataframe such as this:

    df = pd.DataFrame({'Drink': ['Beer', 'Beer', 'Wine', 'Wine', 'Wine', 'Whisky', 'Whisky'], 'Units': [14, 5, 9, 15, 7, 12, 17]})

    Drink Units
    Beer 14
    Beer 5
    Wine 9
    Wine 15
    Wine 7
    Whisky 12
    Whisky 17

    How can I sort the Drink column using a list like this one?

    order = ['Wine', 'Beer', 'Whisky', 'Beer', 'Wine', 'Whisky']


    So that the resulting dataframe looks like this:

    Drink Units
    Wine 9
    Beer 14
    Whisky 12
    Beer 5
    Wine 15
    Whisky 17

    The initial dataframe has more rows than elements in the list, so once everything in the list has matched to a row, the remaining rows can be dropped.

    Continue reading...

Compartilhe esta Página