【问题标题】:unhashable type: 'list' in bag of words不可散列的类型:词袋中的“列表”
【发布时间】:2019-10-04 05:45:34
【问题描述】:

我有两个单词列表,我想要它们的并集。我尝试了下面的方法,但到目前为止没有成功。

bowA = df["Lang_1_text"].str.split(" ") 
bowB = df["Lang_2_text"].str.split(" ") 
print(bowA)
>>>[strike, kirsten, chlodowski, file, exchange]
print(bowB)
>>> [kirsten, exchange, outlook, freeze ]

预期结果:

wordSet = set(bowA).union(set(bowB))

print(wordSet)
>>>[strike, kirsten, chlodowski, file, exchange, outlook, freeze]

实际结果:

TypeError Traceback(最近一次调用最后一次) 在 wordSet = set(bowA).union(set(bowB)) TypeError: unhashable type: 'list'

【问题讨论】:

  • 请显示重现错误的实际代码,以及错误本身,回溯指向代码中它的来源。

标签: python list dataframe hash tuples


【解决方案1】:

这是因为当你这样做时:

bowA = df["Lang_1_text"].str.split(" ") 
bowB = df["Lang_2_text"].str.split(" ") 

bowA 和 bowB 将是一个 Series 对象。 您可以通过打印它们来验证。如下所示:

>> type(bowA)
>> pandas.core.series.Series
>> type(bowA[0])
>> list

Series 中的每个元素都是一个列表。当你将它转换为 set() 时,它会引发 TypeError。 示例:

>> set([1,2,3]) # runs fine
>> set([[1],2,3]) # will raise the same error - TypeError: unhashable type: 'list'

您可能应该执行以下操作:

>> data = {"Lang_1_text": ['strike kirsten chlodowski file exchange'], "Lang_2_text": ['kirsten exchange outlook freeze']} 
>> df = pd.DataFrame(data) # Assuming `df` is the format you have 
>> # Now split it on space " "; and cast them as `set()` you can user `applymap`
>> # https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.applymap.html
>> data_1 = df.applymap(lambda x: set(x.split(" ")))
>> # Calculate the `union` data
>> union_data = data_1.apply(lambda x: x['Lang_1_text'].union(x['Lang_2_text']), axis=1)
>> print union_data.values[0]  # Or list(union_data.values[0]) to make it a list
>> {'chlodowski', 'exchange', 'file', 'freeze', 'kirsten', 'outlook', 'strike'}

希望对你有帮助!

【讨论】:

    【解决方案2】:

    有些东西没有加起来。这段代码对我有用:

    bowA = ['strike', 'kirsten', 'chlodowski', 'file', 'exchange']
    bowB = ['kirsten', 'exchange', 'outlook', 'freeze']
    
    wordSet = set(bowA).union(set(bowB))
    print(wordSet)
    

    虽然您通常可以通过元组转换列表来修复不可散列的类型错误,但存在某种断开,因为散列性在这里并不重要。

    【讨论】:

      猜你喜欢
      • 2019-05-10
      • 2015-07-05
      • 2017-07-11
      • 1970-01-01
      • 2022-01-11
      • 2017-03-14
      • 2020-03-28
      • 2014-02-16
      • 2018-12-26
      相关资源
      最近更新 更多