2

I would like to translate df['Comments'] from whatever language they are in to English and store it in df['Comments_translated'],and just copy paste the value in df['Comments'] to df['Comments_translated'] if the comment is already in English.

import pandas as pd
data = {'text_language':  ['en', 'de','it','unknown', 'ru'],
        'Comments': ['Hello World', 'Hallo Welt', 'Ciao mondo','ciao mon' 'Привет мир']
        }
df = pd.DataFrame (data, columns = ['text_language','Comments'])

#!pip install googletrans
from googletrans import Translator
translator = Translator()
for row in df['Comments']: 
  if df[(df['text_language'] !='en')]:
    df['Comments_translated'] = df['Comments'].apply(translator.translate, dest='en')
  else:
    df['Comments_translated'] = df['Comments']

The code returns:

ValueError                                Traceback (most recent call last)
<ipython-input-24-13044dcbf944> in <module>()
      3 translator = Translator()
      4 for row in TMcopy['Comments']:
----> 5   if TMcopy.loc[(TMcopy['text_language'] !='en')]:
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I have taken a look at this Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() one, but my case, while also a conditional statement, does not contain any numerical values and does not require & | operator..

Luc
  • 737
  • 1
  • 9
  • 22

1 Answers1

1

You can apply function only for rows matched by condition in DataFrame.loc for also select column name:

#!pip install googletrans
from googletrans import Translator
translator = Translator()

mask = df['text_language'] !='en'

df['Comments_translated'] = df['Comments']
f = lambda x: translator.translate(x, dest='en').text
df.loc[mask, 'Comments_translated'] = df.loc[mask, 'Comments'].apply(f)
print (df)
  text_language     Comments Comments_translated
0            en  Hello World         Hello World
1            de   Hallo Welt         Hello World
2            it   Ciao mondo         Hello World
3       unknown     ciao mon           hello mon
4            ru   Привет мир         Hello World
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252