python - 用 pandas dataFrame 中的值填充 python 字典
问题描述
这是我的字典,叫做“评论”:
reviews= {1: {'like', 'the', 'acting'},
2: {'hate', 'plot', 'story'}}
这是我的“词典”数据框:
import pandas as pd
lexicon = {'word': ['like', 'movie', 'hate'],
'neg': [0.0005, 0.0014, 0.0029],
'pos': [0.0025, 0.0019, 0.0002]
}
lexicon = pd.DataFrame(lexicon, columns = ['word', 'neg','pos'])
print (lexicon)
我需要用“lexicon”数据帧中的 neg 和 pos 值填充我的“reviews”字典。
如果词典中没有值,那么我想放 0.5
最终得到这个结果:
reviews= {1: {'like': [0.0005, 0.0025], 'the': [0.5, 0.5], 'acting': [0.5, 0.5]},
2: {'plot': [0.5, 0.5], 'hate': [0.0029, 0.0002], 'story': [0.5, 0.5]}}
解决方案
你可以df.reindex
在这里使用。
df_ = lexicon.set_index("word").agg(list, axis=1)
out = {k: df_.reindex(v, fill_value=[0.5, 0.5]).to_dict() for k, v in reviews.items()}
# {1: {'the': [0.5, 0.5], 'like': [0.0005, 0.0025], 'acting': [0.5, 0.5]},
# 2: {'story': [0.5, 0.5], 'hate': [0.0029, 0.0002], 'plot': [0.5, 0.5]}}
推荐阅读
- java - 找不到构建路径错误的具体原因(Eclipse)
- android - ClassNotFoundException:找不到类“com.google.protobuf.ByteString”
- amazon-dynamodb - 如何在 SwiftUI 中使用 ObservableObject 加载数据?
- php - 如何在 Laravel 中检索 id?
- android - streambuilder firebase上的错误如何解决
- perl - Perl:使用 gzip 打开不存在的 gz 文件时,`die` 不起作用
- python - python Faker模块出现“AttributeError:模块'faker.providers.en_US'没有属性'Provider'”异常
- android - 在Android中的surfaceview初始化后自定义标题下移
- javascript - Angular 8 中库的摇树
- angular - mat-selection-list 与复选框的替代品?