Apply a function to translate a column in pandas dataframe with condition on other columns

2.2k Views Asked by At

data is a pandas dataframe in which language and config['TEXT FIELD'] are columns. I want to translate certain reviews in the text column to english and I am using a function dfApply

import goslate
def dfApply(row):
    if row["langauge"] == 'en':
       return row[config['TEXT FIELD']]
    else:
       return gs.translate(row[config['TEXT FIELD']], 'en')


gs = goslate.Goslate()
data['english_text'] = data.apply(dfApply, axis=1)

But the complier shows the follwing error

KeyError: ('langauge', 'occurred at index 0')
1

There are 1 best solutions below

0
On

Something like this might be an easier approach.

not_en = data["language"] != "en"
trans = translate(data[config['row']], "en")
col = config['row']
data.loc[not_en, col] = trans[not_en]