Home > OS >  Write lambda function to function
Write lambda function to function

Time:10-02

I have a lambda function like this:

from Sastrawi.Stemmer.StemmerFactory import StemmerFactory

factory = StemmerFactory()
stemmer = factory.create_stemmer()

df['tweets_stemming'] = df['tweets_stopwords'].apply(lambda x: [stemmer.stem(stem) for stem in x])

And I want to convert this lambda function to function so I write this:

from Sastrawi.Stemmer.StemmerFactory import StemmerFactory

def stemmer_remover(stemming):
  factory = StemmerFactory()
  stemmer = factory.create_stemmer()
  stemming = [stemmer.stem(stemming) for stemming in df['tweets_stopwords']]

  return stemming

df['tweets_stemming'] = df['tweets_stopwords'].apply(stemmer_remover)

If using lambda function my code runs fine. But, if using function (not lambda) giving an error TypeError: descriptor 'lower' requires a 'str' object but received a 'list'. So, I think because my pandas dataframe from df['tweets_stopwords'] (see the image)

How to fix this?

tweets_stopwords column

CodePudding user response:

Your named function doesn't work the same way as your lambda.

lambda x: [stemmer.stem(stem) for stem in x]

is the same as:

def stemmer_remover(x):
    return [stemmer.stem(stem) for stem in x]

If you replace your lambda expression with the above stemmer_remover you should find that it behaves the same way.

  • Related