[Python] How to set a column which suffix name is based on a value in another column

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

  1. Stack

    Stack Membro Participativo

    #Column X contains the suffix of one of V* columns. Need to put set column V{X} to 9 if X > 1.
    #But my code created a new column 'VX' instead of updating one of the V* columns

    import pandas as pd

    df = pd.DataFrame({'EMPLID': [12, 13, 14, 15, 16, 17, 18],
    'V1': [2,3,4,50,6,7,8],
    'V2': [3,3,3,3,3,3,3],
    'V3': [7,15,8,9,10,11,12],
    'X': [2,3,1,3,3,1,2]
    })

    # Expected output:

    # EMPLID V1 V2 V3 X
    # 12 2 9 7 2
    # 13 3 3 9 3
    # 14 4 3 8 1
    # 15 50 3 9 3
    # 16 6 3 9 3
    # 17 7 3 11 1
    # 18 8 9 12 2


    My code created a new column 'VX' instead of updating one of the V* columns:

    df.loc[(df['X'] > 1), f"V{'X'}"] = 9


    Any suggestion is appreciated. Thank you.

    Continue reading...

Compartilhe esta Página