簡體   English   中英

應用函數以其他列為條件轉換pandas數據框中的列

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

data是一個pandas數據幀,其中language和config ['TEXT FIELD']是列。 我想將文本列中的某些評論翻譯成英文,並且正在使用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')

這樣的事情可能是更容易的方法。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM