[Python] Cannot understand the behaviour of pandas case_when

Discussão em 'Python' iniciado por Stack, Julho 3, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to use the case_when of a pandas Series and I am not sure I understand why it behaves like below. I indicate the behaviour that looks odd to me. It seems it has to do with the index of the Series, but why?

    import pandas as pd
    print(pd.__version__)
    # 2.3.0
    a = pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e'], dtype='int')
    b = pd.Series([1, 2, 3, 4, 5], index=['A', 'B', 'C', 'D', 'E'], dtype='int')
    res = a.case_when(
    [(a.gt(3), 'greater than 3'),
    (a.lt(3), 'less than 3')])
    print(res)
    # a less than 3
    # b less than 3
    # c 3
    # d greater than 3
    # e greater than 3
    res = a.case_when(
    [(a.gt(3), 'greater than 3'),
    (b.lt(3), 'less than 3')])
    print(res)
    # a less than 3
    # b less than 3
    # c less than 3 <- why is this not 3?
    # d greater than 3
    # e greater than 3
    res = a.case_when(
    [(b.gt(3), 'greater than 3'),
    (b.lt(3), 'less than 3')])
    print(res)
    # a greater than 3 <- why is this not less than 3?
    # b greater than 3 <- why is this not less than 3?
    # c greater than 3 <- why is this not 3?
    # d greater than 3
    # e greater than 3
    res = a.case_when(
    [(b.gt(3).to_list(), 'greater than 3'),
    (b.lt(3).to_list(), 'less than 3')])
    print(res)
    # a less than 3
    # b less than 3
    # c 3
    # d greater than 3
    # e greater than 3

    Continue reading...

Compartilhe esta Página