gpt4 book ai didi

python - 将函数应用于 DataFrame 列中的内容并将其保存在另一个中的最佳方法

转载 作者:行者123 更新时间:2023-12-01 06:35:03 24 4
gpt4 key购买 nike

大家好,这就是问题所在,我有一个像这样的 DataFrame:

     item_id  item_title  item_content  title_trans  content_trans0    1        "First"     "Stuff"       NaN          NaN     ...      ...         ...           ...          ...99   100      "Last"      "More stuff"  NaN          NaN

What i intend to do is apply a translation for the title and content column, saving the output to its respective last columns. (Translation will be done with TextBlob or python translate).Output should look like this:

     item_id  item_title  item_content  title_trans  content_trans0    1        "First"     "Stuff"       "Primera"    "Cosas"     ...      ...         ...           ...          ...99   100      "Last"      "More stuff"  "Última"     "Más cosas"

My latest idea was to make a for with DataFrame.iterrows(), and save each output with iloc, kinda like this:

for index, item in DataFrame.iterrows():
raw_text = '\n'.join(item['item_title'], item['item_content'])
trans_text = str(TextBlob(raw_text).translate(to='es'))
title, content = trans_text.split('\n')
DataFrame.iloc(index, 'title_trans') = title
DataFrame.iloc(index, 'content_trans') = content

无论这对于小数据集有多好,如果我将其应用到大量数据集(数千个),我可以看到它会如何开始减慢。有没有一种方法可以映射它或者比 for 循环更有效的方法?

最佳答案

尝试使用应用:

df['title_trans'] = df['item_title'].apply(lambda x: str(TextBlob(x).translate(to='es')))
df['content_trans'] = df['item_content'].apply(lambda x: str(TextBlob(x).translate(to='es')))

关于python - 将函数应用于 DataFrame 列中的内容并将其保存在另一个中的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59710215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com