希望有人能帮我解决这个问题。我正在对一些文本数据进行K-Means聚类。在我的pandas数据框中得到不同的聚类组后,我希望为模型放入数据框的每个聚类组中的“Processed_Data”列的文本创建一个词频列表。创建每个列表后,我希望将它们导出到一个Excel文件中的各个工作表中。对于这段特定代码,我有17个聚类,并希望将17个词频列表导出到一个文件的17个工作表中。
我之前能够分别将每个聚类的数据导出到各自的工作表,并为单个聚类创建词频列表,但在遍历每个聚类组时同时完成这两项任务却没有成功。
示例数据:
|SN |Processed_Data |cluster |
-------------------------------------------------|
|123|hello world good bye world | 01 |
|111|hello world | 01 |
|222|good bye world | 02 |
|555|world great | 02 |
|543|an african or european swallow?| 03 |
|777|what do you mean? | 03 |
我希望根据聚类编号将结果放入各个Excel工作表中:
cluster 01:| word | freq|
---------------|
|world | 3 |
|hello | 2 |
|good | 1 |
|bye | 1 |
cluster 02: | word | freq|
--------------|
|world | 2 |
|great | 1 |
|good | 1 |
|bye | 1 |
ect for each cluster...
这是我尝试过的代码,但似乎对我不起作用。我没有展示所有预处理代码,比如去除大小写、停用词和标点符号,因为我在这方面没有遇到任何问题,而且这增加了帖子的长度。
true_k = 17
model = KMeans(n_clusters=true_k, init='k-means++', max_iter=300, n_init=15)
model.fit(X)
labels=model.labels
data_clusters=pd.DataFrame(list(zip(df['SN'],df['Processed_Data'],labels)),columns=['SN','Processed_Data','cluster'])
data_clusters = data_clusters.sort_values(by=['cluster'])
data_clusters['cluster'] = data_clusters['cluster'].astype(str)
uniques = data_clusters['cluster'].unique()
with pd.ExcelWriter('cluster_test.xlsx') as writer:
for cluster in uniques:
a = data_clusters.loc[data_clusters['cluster'] == cluster][['Processed_Data']].str.cat(sep=' ')
words = nltk.tokenize.word_tokenize(a)
word_dist = nltk.FreqDist(words)
rslt = dict((word, freq) for word, freq in word_dist.items() if not word.isdigit())
rslt = pd.DataFrame(list(word_dist.items()),
columns =['Word', 'Freq'])
rslt = rslt.sort_values(by=['Freq'], ascending=False)
rslt['Cluster'] = cluster
rslt.to_excel(writer, index=None, sheet_name=cluster)
提醒一下,我不得不使用 data_clusters['cluster'] = data_clusters['cluster'].astype(str)
将聚类列转换为字符串,这样Excel写入器就可以用聚类编号命名工作表。使用整数命名工作表时出现了问题。想知道这是否可能是问题的一部分。
回答:
这里是一个解决方案:
import openpyxl
df = pd.DataFrame(
{
'SN': [123,111,222,555,543,777],
'Processed_Data':
['hello world good bye world','hello world', 'good bye world','world great','an african or european swallow?','what do you mean?'],
'cluster' : ['01','01','02','02','03','03']
})
df1 = pd.DataFrame(df.groupby("cluster")["Processed_Data"])
wb = openpyxl.Workbook('Cluster.xlsx')
wb.save('Cluster.xlsx') #Create an excel file
for index, row in df1.iterrows():
print(index)
temp_list = row[1].str.split(' ').tolist()
flat_temp_list = [item for sublist in temp_list for item in sublist]
temp_df = pd.DataFrame({'words': flat_temp_list })
temp_df = temp_df.groupby(["words"])["words"].count().reset_index(name="freq")
with pd.ExcelWriter('Cluster.xlsx',engine="openpyxl", mode="a") as writer:
temp_df.to_excel(writer, sheet_name='Sheet'+str(index))
您的Excel工作表看起来像这样:
words freq
0 bye 1
1 good 1
2 hello 2
3 world 3
words freq
0 bye 1
1 good 1
2 great 1
3 world 2
words freq
0 african 1
1 an 1
2 do 1
3 european. 1
4 mean? 1
5 or 1
6 swallow? 1
7 what 1
8 you 1