比较熊猫中的两个字符串列

时间:2019-09-23 20:34:45

标签: python pandas pd

我需要在熊猫的连续行中比较一组关键字:为了简化起见,我创建了一个列df['next_row'] = df.key_words.shift(-1). 这是df

df = pd.DataFrame({'customer' : [1,1,2,2],
"key_words":[['oil change'], ['oil change', 'filter'], ['leak'], ['leak', 'filter']]}

如果我尝试df['next_row'].isin(df.key_words) 我收到错误消息

TypeError: unhashable type: 'list'

我了解我无法比较列表,而应该使用字符串。 我将next_row转换为字符串:

df.next_row = df.next_row .str.join('|')

现在我可以尝试

df.key_words.str.contains(df['next_row'])

我收到错误消息:

TypeError: 'Series' objects are mutable, thus they cannot be hashed

如何执行逐行比较,以便输出类似于:

df['word_match'] = ['oil change', nan, 'leak', nan]

2 个答案:

答案 0 :(得分:0)

这将提供一个单词列表,该单词列表仅显示根据要求在客户分组中重复出现的单词。

customer_lists = df.groupby('customer')['key_words'].apply(list)
word_match = []

for cust in customer_lists:
    word_match.extend(list(set.intersection(*map(set,cust))))

print(word_match)

答案 1 :(得分:0)

您可以根据需要对其进行修改。将会有NaN,因此您可能也要注意这一点。

 def compare(df):
     for val in df.key_words:
          if isinstance(df.consecutive,list):
              if val in list(df.consecutive):
                  return 'in'
              else:
                  return 'not in'
          elif isinstance(df.consecutive,float): #you might want to check for NaNs here
              continue

 df.apply(compare,axis=1)