1

I am trying the below function.

I want to translate the data in 'Text' from the language it's in, which can be determined through

df['Language'] = df.Text.apply(lambda x: TextBlob(str(x)).detect_language())

Into Spanish, which can be done with:

.translate(from_lang='en', to= 'es')

I have tried the below, but I'm not sure how to nest the two function into a single statement?

df['Translated'] = df.Text.apply(lambda x: TextBlob(str(x)).translate(from_lang= df.Text.apply(lambda x: TextBlob(str(x))), to ='en'))

The input dataframe is just a single column with text statements, like:

Text
"I love this game, I think its great"
"really buggy, not a good experience, do not buy"
"not too bad, not too good"

Can anyone help?

6
  • Do you have an example of your data? Also, have you tried defining a function and not just using lambda functions? Commented Jan 24, 2019 at 21:59
  • any reason you can't just do it in 2 steps? Commented Jan 24, 2019 at 22:00
  • I tried to do it in two steps, but then I wasn't sure how to extract the language from the newly created column and inject it into the change language statement. I'm a bit of a newbee, sorry :( Commented Jan 24, 2019 at 22:02
  • @joepattern I have added my sample data Commented Jan 24, 2019 at 22:02
  • In terms of readability, I would do this in two stages. Don't try cram everything into one line when it affects understanding. You could always have two named functions at the least Commented Jan 24, 2019 at 22:02

1 Answer 1

1

Rather than using Series.apply you can use DataFrame.apply:

df['Translated'] = df.apply(lambda x: TextBlob(str(x.Text)).translate(from_lang=x.Language, to='en'), axis=1)
Sign up to request clarification or add additional context in comments.

2 Comments

Hey thanks for this! I get this error: AttributeError: ("'Series' object has no attribute 'Text'", 'occurred at index Text') - I'm not sure why, because I've been referring to it in all other fields
@kikee1222 my mistake, I forgot the axis=1 kwarg for apply. updated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.