Search code examples
pythonpandasdataframeapply

Check if string in a column, then return value from another column at the same index


Contact Old Contact
234255 987778
343556 987877
Missing 984567
Missing
Missing 845665
343556 789998

Given the table above, I wish to go through each row under "Contact" and check if Missing. If the row has Missing, use corresponding "Old Contact" values inplace of the text 'Missing'. If old contact is empty, then leave it as 'Missing'

Desired table:

Contact Old Contact
234255 987778
343556 987877
984567 984567
Missing
845665 845665
343556 789998
df['Contact'] = df['Contact'].apply(
    lambda x: df['Old Contact'] if "Missing" in x else x)

the line above gives me the whole column of 'Old Contact' where there is Missing. I'm not sure how to use index here to get what I want. Thanks in advance!


Solution

  • use mask

    df['Contact'].mask(df['Contact'].eq('Missing'), df['Old Contact'].fillna('Missing'))
    

    output:

    0      234255
    1      343556
    2      984567
    3     Missing
    4      845665
    5      343556
    Name: Contact, dtype: object
    

    make reult to Contact column