[Python] Replace pandas column value by previous column value if cell contain a substring

Discussão em 'Python' iniciado por Stack, Dezembro 20, 2024.

  1. Stack

    Stack Membro Participativo

    I'm using Python 3.6.8. I have a dataframe df with columns name & sport. I want to replace value of sport if it contains substring "replace this value for".

    My dataframe is generated using following code

    import pandas as pd
    df = pd.DataFrame({'name': ['Bob', 'Jane', 'Alice'],
    'sport': ['tennis', 'replace this value for Jane', 'replace this value for Alice']})


    So I wrote following code

    row_num=df.index[df.iloc[:,1].str.contains('replace this value for')]
    for num in row_num:
    df.loc[num,1]=df.loc[num,0]


    But I'm getting following error

    # If we have a listlike key, _check_indexing_error will raise

    KeyError: 0


    Can you please help me to resolve this error?

    Continue reading...

Compartilhe esta Página