Home > Enterprise >  Ammed a column in pandas dataframe based on the string value in another column
Ammed a column in pandas dataframe based on the string value in another column

Time:04-25

I have a text column with chat information, I want to pass in a list of words that if they appear in that text column will ammend the error column to 1 and 0 if the words do not appear:

chatid text                  card_declined booking_error website_error
401    hi my card declined..        0              0             0
402    you website crashed..        0              0             0
403    hi my card declined..        0              0             0

for example 

carddeclined = ['card declined', 'Card error']

for i in df[df['textchat'].str.contains('|'.join(carddeclined),na=False)]:
    df['card declined'] = 1

This currently just returns all card declined rows with 1

CodePudding user response:

You can assign converted boolean Series to integers, because some upercase values in list is added case=False parameter in Series.str.contains:

carddeclined = ['card declined', 'Card error']

df['card_declined'] = df['text'].str.contains('|'.join(carddeclined),
                                              na=False, 
                                              case=False).astype(int)
print (df)
   chatid                   text  card_declined  booking_error  website_error
0     401  hi my card declined..              1              0              0
1     402  you website crashed..              0              0              0
2     403  hi my card declined..              1              0              0
  • Related