Python : TypeError: 'float' object is not iterable

Debbie picture Debbie · Sep 26, 2018 · Viewed 8.4k times · Source

I am trying to remove stopwords from Pandas dataframe. This is my code:

import nltk
from nltk.corpus import stopwords
nltk.download('stopwords')

stop_words = stopwords.words('english')
print(stop_words)

data['description'] = data['description'].apply(lambda x: [item for item in x if item not in stop_words])

Output:

['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've", "you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', "she's", 'her', 'hers', 'herself', 'it', "it's", 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', "that'll", 'these', 'those', 'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after', 'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so', 'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don', "don't", 'should', "should've", 'now', 'd', 'll', 'm', 'o', 're', 've', 'y', 'ain', 'aren', "aren't", 'couldn', "couldn't", 'didn', "didn't", 'doesn', "doesn't", 'hadn', "hadn't", 'hasn', "hasn't", 'haven', "haven't", 'isn', "isn't", 'ma', 'mightn', "mightn't", 'mustn', "mustn't", 'needn', "needn't", 'shan', "shan't", 'shouldn', "shouldn't", 'wasn', "wasn't", 'weren', "weren't", 'won', "won't", 'wouldn', "wouldn't"]

TypeError                                 Traceback (most recent call last)
<ipython-input-124-b9f65f003ed5> in <module>()
      7 #word_tokens = word_tokenize(data['description'])
      8 print('---------------------------------------------------------')
----> 9 data['description'].apply(lambda x: [item for item in x if item not in stop_words])
     10 print('---------------------------------------------------------')
     11 print(data.description[0])

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds)
   2549             else:
   2550                 values = self.asobject
-> 2551                 mapped = lib.map_infer(values, f, convert=convert_dtype)
   2552 
   2553         if len(mapped) and isinstance(mapped[0], Series):

pandas/_libs/src/inference.pyx in pandas._libs.lib.map_infer()

<ipython-input-124-b9f65f003ed5> in <lambda>(x)
      7 #word_tokens = word_tokenize(data['description'])
      8 print('---------------------------------------------------------')
----> 9 data['description'].apply(lambda x: [item for item in x if item not in stop_words])
     10 print('---------------------------------------------------------')
     11 print(data.description[0])

TypeError: 'float' object is not iterable

I think the error is coming from this part:

[item for item in x if item not in stop_words]

But it's clear that stop_words is a list. Then?

Edit 1:

I made following changes to my code:

data['description'] = data['description'].str.split()
print(data.description[679])
data['description'] = data['description'].apply(lambda x: [item for item in x if item not in stop_words])

split() works perfectly. This is the content of data.description[679]:

['ame', 'jalsa', 'event', 'presents', 'navratri', 'jhankaar', 'premium', 'navratri', 'and', 'lifestyle', 'exhibition', 'september', 'seema', 'hall', 'anand', 'nagar', 'road', 'near', 'sachin', 'tower', 'ahmedabad', 'visit', 'meet', 'over', 'designers', 'from', 'all', 'over', 'india', 'perfect', 'navratri', 'stuff', 'shopping', 'created', 'ame', 'jalsa', 'event', 'dont', 'miss', 'this', 'grand', 'exhibition', 'navratri', 'exhibition', 'premium', 'exhibition', 'lifestyle', 'fashion', 'accessories', 'jewellery', 'jalsa', 'jalsa', 'jalsa', 'exhibition', 'jalsaaholics', 'jalsa', 'ahmedabad', 'shopping']

Still the error persists.

Answer

jezrael picture jezrael · Sep 26, 2018

I think there are missing values, so possible solution is remove them by dropna - after assign to column back are created again:

data['description'] = (data['description'].dropna()
                         .apply(lambda x: [item for item in x if item not in stop_words]))

If need remove all rows with missing values NaNs in column description:

data = data.dropna(subset=['description'])
data['description'] = (data['description']
                        .apply(lambda x: [item for item in x if item not in stop_words]))

Or if need empty lists for missing values:

data = pd.DataFrame({
    'description': ['i love','a me you',None,'ahoj', np.nan],
    'B': list(range(5))
})

data['description'] = data['description'].str.split()
print (data)
    description  B
0     [i, love]  0
1  [a, me, you]  1
2          None  2
3        [ahoj]  3
4           NaN  4

stop_words = ['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've", "you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', "she's", 'her', 'hers', 'herself', 'it', "it's", 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', "that'll", 'these', 'those', 'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after', 'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so', 'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don', "don't", 'should', "should've", 'now', 'd', 'll', 'm', 'o', 're', 've', 'y', 'ain', 'aren', "aren't", 'couldn', "couldn't", 'didn', "didn't", 'doesn', "doesn't", 'hadn', "hadn't", 'hasn', "hasn't", 'haven', "haven't", 'isn', "isn't", 'ma', 'mightn', "mightn't", 'mustn', "mustn't", 'needn', "needn't", 'shan', "shan't", 'shouldn', "shouldn't", 'wasn', "wasn't", 'weren', "weren't", 'won', "won't", 'wouldn', "wouldn't"]

f = lambda x: [item for item in x if item not in stop_words] if isinstance(x, list) else []
data['description'] = data['description'].apply(f)

print (data)
  description  B
0      [love]  0
1          []  1
2          []  2
3      [ahoj]  3
4          []  4