【问题标题】:Pandas: Each row take a string, separate by commas, and add unique word to listPandas:每行取一个字符串,用逗号分隔,并将唯一的单词添加到列表中
【发布时间】:2020-08-07 19:55:39
【问题描述】:

样本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']]

这是为每一行添加唯一值,但不是每行中的单词。因此,即使我尝试拆分 ,,它仍然将整个文本视为一个文本,而不是使用字符串中的单个单词。

【问题讨论】:

    标签: python pandas dataframe split


    【解决方案1】:

    使用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']
    

    【讨论】:

      猜你喜欢
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 2019-01-23
      • 2018-05-08
      • 2017-04-10
      • 2017-07-25
      • 2015-11-22
      • 2022-01-26
      相关资源
      最近更新 更多