0
$\begingroup$

I have a survey df and I want to assign a new value of either existing customer or new customer based on their answers. if someone has 3 answers but one of them matches "coca cola" I want to give them the value of existing customer here is the data frame

ID       Question                                                Answer
101005   what brands did you purchase the past 5 months   Coca-Cola or Pepsi or vitamin water
026458   what brands did you purchase the past 5 months           None
045987   what brands  did you purchase the past 5 months        Coca-Cola

Here is the table I would like to have

ID        Question                                          Answer                      Buyer_Type
101005   what brands did you purchase the past 5 months  Coca-Cola,Pepsi,fanta          Existing Users          
026458   what brands did you purchase the past 5 months  None                           New Buyer              
045987   what brands did you purchase the past 5 months  Coca-Cola                      Existing Users

Here is what I tried

deux['Buyer_Type'] = deux['answer'].apply(lambda x: 'existing buyer' if x == 'Coca-Cola' else 'new buyer')

For some reasons it is not recognizing 101005 as an existing user.

$\endgroup$
1
$\begingroup$

You are not getting the results you're expecting because you're explicitly comparing the value in the Answer column to 'Coca-Cola' (i.e x == 'Coca-Cola') but the value in that column is (I'm assuming) a list or a string. In either case comparing it to 'Coca-Cola' would result in False.
What you need to do is change your condition to check in 'Coca-Cola' appears anywhere in the list or string.
Here's one way of achieving this (I'm assuming the Answer column contains lists):

import pandas as pd

data = {
          "ID": ["101005", "026458", "045987"], 
          "Question": ["what brands did you purchase the past 5 months", 
                       "what brands did you purchase the past 5 months",
                       "what brands did you purchase the past 5 months "],
          "Answer": [["Coca-Cola" ,"Pepsi" ,"fanta"], [None], ["Coca-Cola"]]
}
deux = pd.DataFrame(data)
deux['Buyer_Type'] = deux['Answer'].apply(lambda x: 'existing buyer' if 'Coca-Cola' in x else 'new buyer')
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.