Search code examples
pythonfunctionapply

Return 2 values in 2 columns


Do you know if it was possible to return 2 values in 2 columns with one def?

I have this two def:

def codeAcro (row):
    NOVA, Concordance = row['Code'], row['Concordance']
    if pd.isna(Concordance) == True:
        return None
    else:
        return Concordance

ListeCodeNova['Acronyme'] = ListeCodeNova[['Concordance','Code']].apply(codeAcro, axis=1)

def codeNOVA (row):
    NOVA, Concordance = row['Code'], row['Concordance']
    if pd.isna(Concordance) == True:
        return None
    else:
        return NOVA

ListeCodeNova['Concordance'] = ListeCodeNova[['Concordance','Code']].apply(codeNOVA, axis=1)

And i want to know if it was possible to simplify in just one def.


Solution

  • For performance more better to avoid the apply method (which is called for every row), and use boolean indexing instead:

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'Concordance':[1, np.nan, 2], 'Code':[10, 11,12]})
    mask = df.Concordance.notna()
    df['Acronyme'] = np.where(mask, df.Concordance, None)
    df['Concordance'] = np.where(mask, df.Code, None)