Search code examples
pythonpandasdataframepandas-apply

Changing values (with apply) in one column of pandas dataframe depending on particular values in other column in this dataframe with mask


I have a dataframe:

df = pd.DataFrame({'col1': [69, 77, 88],
                   'col2': ['barf;', 'barf;', 'barfoo']})
print(df, '\n')

   col1    col2
0    69   barf;
1    77   barf;
2    88  barfoo 

Also i have selection function:

def selection_func(string):
    '''
    Function returns a, if string is 'barf;'
    '''
    if string == 'barf;':
        return 'a'
    else:
        return string

So I need to change particular values (not all) in col2 with condition based on col1:

condition = (df['col1'] == 69) | (df['col1'] == 88)

Desired output:

   col1    col2
0    69       a
1    77   barf;
2    88  barfoo

Solution

  • Found a solution while was writing the question:

    df.loc[condition, 'col2'] = df.loc[condition, 'col2'].apply(func)
    print(df, '\n')
    
       col1    col2
    0    69       a
    1    77   barf;
    2    88  barfoo