【问题标题】:python creating nested dictionary counter issuepython创建嵌套字典计数器问题
【发布时间】:2021-08-25 14:44:54
【问题描述】:

我正在研究单词出现与响应变量之间的相关性。为此,我正在尝试创建具有以下结构的字典:

{word_1:{response_value:word_1_occurrence_with_same_response_value},
 word_2:{response_value:word_2_occurrence_with_same_response_value}...}

看起来一切正常,除了我的代码的最后一行。

以下是一些数据示例:

data = pd.DataFrame({
    'message': ['Weather update', 'the Hurricane is over',
                'Checking the weather', 'beautiful weather'],
    'label': [0, 1, 0, 1]
})

和我的代码:

word_count = {}

for idx,msg in enumerate(data['message']):
    msg = msg.lower()
    label = data['label'][idx]
    for word in msg.split():
        word_count[word]={}
        word_count[word][label]=word_count.get(word,0)+1

我收到以下错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-72-b195c90ef226> in <module>
      6     for word in msg.split():
      7         word_count[word]={}
----> 8         word_count[word][label]=word_count.get(word,0)+1

TypeError: unsupported operand type(s) for +: 'dict' and 'int' 

我试图获得的输出如下

{'weather': {0: 2}, 'update': {0: 1},'the': {1: 1},'hurricane': {1: 1},
 'is':{1:1},'over':{1:1}, 'checking':{0:1},'the':{0:1},'weather':{1:1},
 'beautiful':{1:1}}

我尝试了各种解决方案,但无法让计数器正常工作,只能为键分配值。
我在这里也只找到了关于从已经存在的嵌套字典中计数的帖子,而这里正好相反,但是,如果我错过了,请引导我到相应的帖子。

谢谢

【问题讨论】:

  • 您提供的示例数据的输出应该是什么样的?
  • 请注意,使用collections.defaultdict可以大大简化您的代码
  • 您试图获得的输出在 python 中是不可能的,因为它是一个字典,并且“天气”键是重复的。 python 字典中的键是唯一的。我认为你需要重新考虑你想要的输出。

标签: python pandas counter


【解决方案1】:

无法在 python 中获得所需的输出,因为字典中的同一个键不能有两个不同的值。键必须是唯一的。这是我想出的:

data = pd.DataFrame({
    'message': ['Weather update', 'the Hurricane is over',
                'Checking the weather', 'beautiful weather'],
    'label': [0, 1, 0, 1]
})

word_count = {}

for idx,msg in enumerate(data['message']):
    msg = msg.lower()
    label = data['label'][idx]
    for word in msg.split():
        word_count[word][label] = word_count.setdefault(word, {}).setdefault(label, 0)+1

print(word_count)

输出:

{'weather': {0: 2, 1: 1}, 'update': {0: 1}, 'the': {1: 1, 0: 1}, 'hurricane': {1: 1}, 'is': {1: 1}, 'over': {1: 1}, 'checking': {0: 1}, 'beautiful': {1: 1}}

【讨论】:

    猜你喜欢
    • 2023-01-18
    • 2021-04-04
    • 2019-05-29
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多