dimanche 16 décembre 2018

Returning all the 'if conditions values' in a separate column

I have a data frame, on which I am applying 'if' condition to return certain vales. I want to create a new column which will have those values but in cases where multiple conditions are satisfied, I want all the 'return' values in that column

For the following dataframe, for instance

sample = pd.DataFrame({'Status':('reliable','non-reliable','reliable','non-reliable','reliable','reliable','non-reliable'),
                       'Gender': ('M','M','F','M','F','M','F'),
                       'Domain': ('Yes','No','Yes','No','Yes','No','Yes'),
                       'Paid': ('Paid','Paid','Paid','Not Paid','Paid','Not Paid','Paid')
        })

Sample conditions are as follows. For instance if 'Status is reliable and Gender is F', the new column should have both the return value 'reliable True' and 'F True'

def sample_column(row):
    if ((row['Status'] == 'reliable')):
        return 'reliable True'
    if ((row['Gender'] == 'F')):
        return 'F True'
    if ((row['Domain'] == 'Yes')):
        return 'Doamin True'

Finally building the column

sample = sample.assign(True_cases = sample.apply(sample_column,axis=1))

I found one sample solution here (but I am not able to replicate): Check every condition in Python if else even if one evaluates to true

Any help in this regard will be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire