[Python] Replacing values in columns with values from another columns according to mapping

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

  1. Stack

    Stack Membro Participativo

    I have this kind of dataframe:

    df = pd.DataFrame({
    "A1": [1, 11, 111],
    "A2": [2, 22, 222],
    "A3": [3, 33, 333],
    "A4": [4, 44, 444],
    "A5": [5, 55, 555]
    })

    A1 A2 A3 A4 A5
    0 1 2 3 4 5
    1 11 22 33 44 55
    2 111 222 333 444 555


    and this kind of mapping:

    mapping = {
    "A1": ["A2", "A3"],
    "A4": ["A5"]
    }


    which means that I want all columns in list to have values from key column so: A2 and A3 should be populated with values from A1, and A5 should be populated with values from A4. Resulting dataframe should look like this:

    A1 A2 A3 A4 A5
    0 1 1 1 4 4
    1 11 11 11 44 44
    2 111 111 111 444 444


    I managed to do it pretty simply like this:

    for k, v in mapping.items():
    for col in v:
    df[col] = df[k]


    but I was wondering if there is vectorized way of doing it (more pandactic way)?

    Continue reading...

Compartilhe esta Página