从列中获取唯一的单词并将它们放在新列中
我尝试了以下代码,但它不起作用:
query=list(train['doc_text'].str.split(' ', expand=True).stack().unique())
这是一个数据示例:
Train
Row Doc_text Count
0 this is a book 4
1 my taylor is rich 4
2 apple a day 3
以下是预期输出的示例:
Dfnew
Row Uniquewords
0 this
1 is
2 a
3 book
4 my
5 taylor
6 rich
7 apple
8 day
我想在列表中获取单词,然后能够将此列表保存为新数据集。
你也可以这样做:
unique_list = []
for i in df['Uniquewords']:
[unique_list.append(word) for word in i.split() if word not in unique_list]
您可以使用此unique_list
,也可以将此列表写入数据帧。
df_new = pd.DataFrame(unique_list, columns=['Unique_words'])
IIUC您需要以下内容:
df_new=pd.DataFrame(train['doc_text'].str.split(' ', expand=True).stack().unique(),\
columns=['Uniquewords']).reset_index().rename(columns={'index':'Row'})
print(df_new)
Row Uniquewords
0 0 this
1 1 is
2 2 a
3 3 book
4 4 my
5 5 taylor
6 6 rich
7 7 apple
8 8 day