【问题标题】:Converting value of a dictionary of lists to floats将列表字典的值转换为浮点数
【发布时间】:2021-05-13 11:46:41
【问题描述】:

这里是 Python 新手!我真的可以在我用 Python 做的情感项目上得到一些帮助。

我已经建立了这本字典,我想用它来浏览我从 Guardian 文章中摘录的 cmets。我想在guardian_comments 数据框中添加一个额外的列,表示sentiment_score 列中的值是very_negative、negative、neutral、positive 还是very_positive:

lookup_dict = {
"very_negative":[-0.9, -0.8, -0.7, -0.6], 
"negative":[-0.5, -0.4, -0.3, -0.2, -0.1],
"neutral":[0],
"positive":[0.1, 0.2, 0.3, 0.4, 0.5], 
 "very_positive":[0.6, 0.7, 0.8, 0.9, 1]}

guardian_comments['sentiment_level'] = guardian_comments['sentiment_score'].map(lambda x: lookup_dict[x])

但是,我收到了KeyError,我认为这是因为字典列表尚未转换为浮点数。谁能建议我如何做到这一点?

谢谢!

【问题讨论】:

  • 您的代码片段远不是有用的minimal reproducible example,而且似乎与将事物转换为浮点数无关。键不是浮动的,所以这不太可能是问题。
  • 也许问题在于您试图使用包含在 values 中的浮点数作为键来查找相应的 key。如果是这样,那不是您使用字典的方式。你需要反转你的字典。

标签: python list dictionary type-conversion


【解决方案1】:

lookup_dict[x] 使用键 x 检索 lookup_dict 中的条目。
例如lookup_dict["very_negative"] 将返回 [-0.9, -0.8, -0.7, -0.6]lookup_dict[-0.6] 将导致 KeyError
所以你的 lambda 函数并不像你想象的那样。

我认为最简单的解决方案是这样的:

lookup_dict = {
    -0.9:"very_negative",
    -0.8:"very_negative",
    -0.7:"very_negative",
    -0.6:"very_negative",
    -0.5:"negative",
    -0.4:"negative",
    -0.3:"negative",
    -0.2:"negative",
    -0.1:"negative",
    0:"neutral",
    0.1:"positive",
    0.2:"positive",
    0.3:"positive",
    0.4:"positive",
    0.5:"positive",
    0.6:"very_positive",
    0.7:"very_positive",
    0.8:"very_positive",
    0.9:"very_positive",
    1:"very_positive"
}

guardian_comments['sentiment_level'] = guardian_comments['sentiment_score'].map(lambda x: lookup_dict[x])

【讨论】:

  • 非常感谢,这解决了我的问题!
【解决方案2】:

如果您希望保持字典的当前结构,最容易做到这一点的方法是定义一个辅助函数,您可以将其作为 lambda 应用到字典中:

def find_level(row):
    for key, value in lookup_dict.items():
        if row['sentiment_score'] in value:
            return key

df['sentiment_level'] = df.apply(lambda row: find_level(row), axis = 1)

#output:
   sentiment_score sentiment_level
0             -0.5        negative
1              0.5        positive
2              0.6   very_positive
3             -0.2        negative
4             -0.1        negative

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-25
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 2020-09-07
    • 1970-01-01
    • 2019-01-25
    相关资源
    最近更新 更多