'Split translation results with pandas in Google Colab

Hi everyone I'm doing a traslation of words in csv/excel files using Google Colab and Pandas here is my code:

import pandas as pd
from googletrans import Translator 
# read from an excel file
df = pd.read_excel('/content/Libro2.xlsx')
translator = Translator()  
df = df.apply(translator.translate,src='en',dest='es').apply(getattr, args=('text',))

So basically my input from excel is this one: enter image description here

My output is this with this line in specific df = df.apply(translator.translate,src='en',dest='es').apply(getattr, args=('text',)) so the problem here is I'm getting the format for a csv file, I would like to keet it with the format of the input, so I would like to have my data frame to export in to csv as usual. Here is my output: enter image description here

The output that I would like to have is like the first image just in case is not clear my issue. Help please and thanks!



Solution 1:[1]

If you need to apply the function elementwise, you can use Pandas applymap.

df = pd.DataFrame(['the quick brown fox jumps over the lazy dog'.split()])

translator = Translator()
df_tr = df.applymap(lambda w: translator.translate(w, src='en',dest='es').text)
print(df_tr)

Output df_tr

    0       1       2      3      4          5   6     7      8
0  la  rápido  marrón  zorro  salta  terminado  la  vago  perro

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 n1colas.m