Python : TypeError: 'float' object is not iterable

Python : TypeError: 'float' object is not iterable

我正在尝试从 Pandas 数据框中删除停用词。这是我的代码:

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])

输出:

['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

我认为错误来自这部分:

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

但是很明显stop_words是一个列表。然后呢?

编辑 1:

我对我的代码进行了以下更改:

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() 完美运行。这是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']

错误仍然存​​在。

我认为存在缺失值,因此可能的解决方案是通过 dropna 删除它们 - 在重新创建分配给列后:

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

如果需要删除第 description 列中缺少值 NaN 的所有行:

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

或者如果需要缺失值的空列表:

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