[Python] Create a new dataframe column from if else and list comprehension [duplicate]

Discussão em 'Python' iniciado por Stack, Junho 16, 2025.

  1. Stack

    Stack Membro Participativo

    I have two address columns and want to create a third column based on a condition. The condition is - if the '/' symbol exists in 'ADDRESS1' column then concatenate 'ADDRESS1' & 'ADDRESS2' columns. If this symbol, does not exist in the column row return only 'ADDRESS1'.

    ADDRESS1 ADDRESS2 new col
    26 KERR STREET 26 KERR STREET
    FLAT 3/4 51 MAIN STREET FLAT 3/4 51 MAIN STREET

    I tried the below:

    df['newcol'] = [df['ADDRESS1'] + df['ADDRESS2'] if a.find('/') > 0 else df['ADDRESS1'] for a in df['ADDRESS1']]


    my 'new col' seems to be combining all previous rows of data in this crazy string...

    ADDRESS1 ADDRESS2 new col
    26 KERR STREET {"0":"72 BELLROCK CRESCENT","1":"22 KERR STREET","2":"80 GLENACRE DRIVE","3"
    FLAT 3/4 51 MAIN STREET "14":null,"15":null,"16":null,"17":null,"18":"FLAT 3/451 MAIN STREET"

    not sure what am I doing wrong and how to make it work

    Continue reading...

Compartilhe esta Página