lundi 14 août 2017

Python : How to use if elif for rows in a dataframe

I have a dataframe and i want to add a columns using if elif condition on the rows of the table. I am using if elif statement but that is not working. Can we not use the conditional statememt for a data frame?

Here is my code:

import pandas as pd
df = pd.DataFrame({'c1': ['a', 'a', 'q', 'a'],
              'c2': ['b', 'e', 'b', 'f'],
               'c3': ['c', 'f', 'c', 'd']})

if [(df['c1']=='s') & (df['c2']=='b')]:
    df['q']= df['c1'] + '+' + df['c2']
elif (df['c1']=='a' & df['c2']=='f'):
    df['q'] = df['c1'] + '*' + df['c2']
else:
    df['q'] = df['c1'] + '-' + df['c2']

Aucun commentaire:

Enregistrer un commentaire