jeudi 2 mai 2019

How to apply wildcard in python pandas dataframe?

I have one dataframe:

Car       Color 
BMW       WHITE
BMPrO     Black
Toyota    Green
Honda     Black

I wish to create a column which based on the Car column, if Car column start with BM* then ID column will be A IF Car column startwith T then ID column will be B else C

Expected dataframe

Car       Color   ID
BMW       WHITE   A
BMPrO     Black   A
Toyota    Green   B
Honda     Black   C

Anyone have ideas?

I have try this code but not work for this case:

def f(row):
if row['car']=='B*':
    val = A
elif row['Car'] =='T*':
    val = B
else:
    val = 'C'
return val
df['ID'] = df.apply(f, axis=1)

Aucun commentaire:

Enregistrer un commentaire