应用函数来转换pandas dataframe中的列,其他列上的条件

时间:2015-09-03 12:05:30

标签: python pandas apply goslate

数据是一个pandas数据框,其中语言和配置[' TEXT FIELD']是列。我想将text列中的某些评论翻译成英语,我正在使用函数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)

但是编译器显示了以下错误

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

1 个答案:

答案 0 :(得分:0)

这样的事情可能更容易。

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