[Python] confusion on re-assigning pandas columns after modification with apply

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

  1. Stack

    Stack Membro Participativo

    Let us assume we have this dataframe:

    df = pd.DataFrame.from_dict({1:{"a": 10, "b":20, "c":30}, 2:{"a":100, "b":200, "c":300}}, orient="index")

    Further, let us assume I want to apply a function to each row that adds 1 to the values in columns a and b

    def add(x):
    return x["a"] +1, x["b"] +1


    Now, if I use the apply function to mod and overwrite the columns twice, some values are flipped:

    >>> df.loc[:, ["a", "b"]] = df[["a", "b"]].apply(lambda x: add(x), axis=1)
    >>> df
    a b c
    1 11 101 30
    2 21 201 300
    >>>
    >>> df.loc[:, ["a", "b"]] = df[["a", "b"]].apply(lambda x: add(x), axis=1)
    >>> df
    a b c
    1 12 22 30
    2 102 202 300
    >>>


    Could somebody explain to me why b1 and a2 get flipped?

    Continue reading...

Compartilhe esta Página