【发布时间】: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