对于当前项目,我想遍历Pandas DataFrame中定义为common_words
的单词对列表。
但是,在致电for word in common_words:
时,我收到错误消息TypeError: 'NoneType' object is not iterable
。我已经检查了解决此问题的可能方法,但尚未找到任何解决方案。
是否有任何智能调整可进行此操作?
相应的代码部分如下所示:
# Open the file to write to
with open('sp500-1.csv', 'w', newline='') as file:
writer = csv.writer(file)
# Write headers
writer.writerow(["Section", "TFI"])
# Loop over the JSON objects
for i in ['txt_pro','txt_con','txt_adviceMgmt','txt_main']:
# Loop over the common words inside the JSON object
common_words = get_top_n_bigram_Group2(df[i], 500)
for word in common_words:
# Print and write row.
print(df2)
writer.writerow([df2])
get_top_n_bigram_Group2
的定义如下:
def get_top_n_bigram_Group2(corpus, n=None):
# settings that you use for count vectorizer will go here
tfidf_vectorizer=TfidfVectorizer(ngram_range=(2, 2), stop_words='english', use_idf=True).fit(corpus)
# just send in all your docs here
tfidf_vectorizer_vectors=tfidf_vectorizer.fit_transform(corpus)
# get the first vector out (for the first document)
first_vector_tfidfvectorizer=tfidf_vectorizer_vectors[0]
# place tf-idf values in a pandas data frame
df1 = pd.DataFrame(first_vector_tfidfvectorizer.T.todense(), index=tfidf_vectorizer.get_feature_names(), columns=["tfidf"])
df2 = df1.sort_values(by=["tfidf"],ascending=False)
print(df2)
答案 0 :(得分:1)
此函数不返回任何内容,
# Loop over the common words inside the JSON object
common_words = get_top_n_bigram_Group2(df[i], 500)
如果您熟悉C,C#,C ++或Java之类的其他语言,则就像在函数之前使用void关键字一样, get_top_n_bigram_Group2()在其他语言中返回null或null,但是python使用None和Error
TypeError:“ NoneType”对象不可迭代
告诉您它不是像字符串,列表,字典或元组那样的迭代器,因此您不能为它们使用索引,或者在这种情况下不能用于循环。