样本df:
filldata = [['5,Blue,Football', 3], ['Baseball,Blue,College,1993', 4], ['Green,5,Football', 1]]
df = pd.DataFrame(filldata, columns=['Tags', 'Count'])
我想要该列中使用的单词的唯一列表Tags
。因此,我试图遍历df并拉出的每一行Tags
,拆分,
并添加单词到列表中。我可以只检查并添加唯一的单词,也可以全部添加它们,然后仅添加唯一的单词。如果可能的话,我想为这两种方法提供解决方案,以查看哪种方法更快。
因此,预期输出应为:
5, Blue, Football, Baseball, College, 1993, Green
。
我已经尝试过这些:
tagslist = df['Tags'][0].split(',') # To give me initial starting words
def adduniquetags(newtags, tagslist):
thesetags = newtags.split(',')
tagslist = tagslist.extend(thesetags)
return tagslist
tagslist = [adduniquetags(row, tagslist) for row in df['Tags']]
和
tagslist = df['Tags'][0].split(',')
def adduniquetags(newtags, tagslist):
thesetags = newtags.split(',')
for word in thesetags:
if word not in tagslist:
tagslist.append(word)
tagslist = [adduniquetags(row, tagslist) for row in df['Tags']]
这两个本质上是相同的,一个只寻找唯一的单词。这两个都返回“无”列表。
我也尝试过这个:
tagslist = df['Tags'][0].split(',')
def adduniquetags(newtags, tagslist):
thesetags = newtags.split(',')
tagslist = list(set(tagslist + thesetags))
return tagslist
tagslist = [adduniquetags(row, tagslist) for row in df['Tags']]
这是为每一行添加唯一值,而不是每一行中的单词。因此,即使我尝试对进行拆分,
,它仍将整个文本视为一个文本,而不是使用字符串中的单个单词。
使用Series.str.split
到分裂的字符串,然后使用np.hstack
到堆栈水平列所有列表Tags
,下次使用np.unique
此堆叠阵列上,找到数组的独特元素。
lst = np.unique(np.hstack(df['Tags'].str.split(','))).tolist()
使用Series.explode
+的另一个可能的想法Series.unique
:
lst = df['Tags'].str.split(',').explode().unique().tolist()
结果:
['1993', '5', 'Baseball', 'Blue', 'College', 'Football', 'Green']
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句