[Python] Change values in one column on the basis of the values in another column

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

  1. Stack

    Stack Membro Participativo

    I'm trying to reproduce my Stata code in Python, and I was pointed in the direction of Pandas. I am, however, having a hard time wrapping my head around how to process the data.

    Let's say I want to iterate over all values in the column head 'ID.' If that ID matches a specific number, then I want to change two corresponding values FirstName and LastName.

    In Stata it looks like this:

    replace FirstName = "Matt" if ID==103
    replace LastName = "Jones" if ID==103


    So this replaces all values in FirstName that correspond with values of ID == 103 to Matt.

    In Pandas, I'm trying something like this

    df = read_csv("test.csv")
    for i in df['ID']:
    if i ==103:
    ...


    Not sure where to go from here. Any ideas?

    Continue reading...

Compartilhe esta Página