0

I have a three-part question - I have three lists and I'm trying to write a loop to iterate over either two of lists to assign a value to a new column based on a match (or through the list of lists). When I assign it to the column like below it only prints the else value or whatever number in the last condition. Thank you in advance.

  1. Why is that?

  2. How do I format this loop?

  3. Can someone write a better for loop that iterates over all_names assigning 1 to a match from all_names[0] and 2 for a match all_names[1]? - does enumerate work for that?

    first_names = ['David', 'Dani', 'Declan']
    second_names = ['Katz', 'Foley', 'Stevenson']
    all_names = [first_names, second_names]
    
    for row in df['name']:
        for elem in firstname_list:
           if elem in row:
              df['name_num']= 1
        for elem in secondname_list:
           if elem in row:
              df['name_num']= 2
        else:
             df['name_num']= 3 
    
Digital Moniker
  • 281
  • 1
  • 12

1 Answers1

1

Check with np.select:

df['name_num'] = np.select( (df['name'].isin(first_names), 
                             df['name'].isin(second_names) ),
                            (1,2), 3)
                         
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74