pythondataframelistdictionaryreplace

Iterating and updating a column using a list


 originallist = df['Customer'].tolist()

I have an list of customers. Within these customers, i have some translations to do which i have done. In other words, i iterate through the original list of about 4000 customers, find about 1500 entries that need to be translated and they can be anywhere in that original list/column. I now need to replace/map/update the entries with the updated translated customer.

 translated_customer = (translator.translate(customer).text)

How do I go about this? If it was one entry, all fine and good, but its because i have a list, its more complicated

Example Column 
these
are
all
good 
words
bien
bonjour
hello
word

I have the above list, iterate through, find those french words say, translate those words and now i need to update these words by slotting them back into the original list

  Example Column
these
are
all
good 
words
good
hello
hello
word

ignore duplicates


Solution

  • You can do this by mapping or updating the translated customers back to their original positions in the dataframe. To handle this for a list of customer entries, you can create a dictionary mapping the original customer names to their translated values, then use this dictionary to update the Dataframe.

    Step 1: Create an empty dictionary to store translations. Step 2: Iterate through the original list of customers.

    I will give you the full code for this.

    # Step 1: Create a dictionary to store translations
    translations = {}
    
    # Step 2: Iterate over the original customer list and translate customers
    for customer in df['customer']
      if customer_needs_translation(customer): # This is the condition to check if the customer needs translation
          translated_customer = trnaslator.trnaslate(customer).text
          translations[customer] = trnaslated_customer
    
    # Step 3: Use the dictionary to map and replace the translated customers
    df['Customer'] = df['Customer'].map(lambda x: translations.get(x,y))