1

I have a dataframe with 205232 rows, i want to translate the column 'ingredients_text' which can contain 1 or more languages in a single row to english. This is an example of the df

enter image description here

I I tried the translation with two ways but it didn't work: code 1:

import googletrans    
from googletrans import Translator
translator = Translator()
df['transalted']= df['ingredients_text'].apply(translator.translate ,dest='en').apply(getattr, args=('text',))
#then i want to save the result into a csv file

code 2:

import googletrans
from googletrans import Translator
translator = Translator()
for column in df['ingredients_text']: 
   translation=translator.translate(column, dest='fr').text
#then i want to save the result into a csv file

I greatly appreciate your help.

Yoss
  • 466
  • 2
  • 4
  • 13

1 Answers1

2

Try apply() with lambda function. Then use pandas.DataFrame.to_csv() to convert dataframe to csv.

import googletrans    
from googletrans import Translator


translator = Translator()
df['transalted'] = df['ingredients_text'].apply(lambda x: translator.translate(x, dest='en').text)

df.to_csv('your.csv')

# If you only want translated result,
# you can use
df['transalted'].to_csv('your.csv')
Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52
  • the traslation works well, but save it in csv makes an error : OSError: [Errno 95] Operation not supported: 'translated.csv' – Yoss Apr 22 '21 at 10:45
  • @Yoss `df.to_csv('your.csv')` and `df['transalted'].to_csv('your.csv')` which one are you using? You only need to choose one of them. – Ynjxsjmh Apr 22 '21 at 10:47
  • i need to save all the df => df.to_csv('your.csv') , i'm using google colab – Yoss Apr 22 '21 at 11:11
  • @Yoss I don't use google colab. Check [Export dataframe as csv file from google colab to google drive](https://stackoverflow.com/questions/53898836) for pandas exportation. – Ynjxsjmh Apr 22 '21 at 11:19