簡體   English   中英

用 pandas dataFrame 中的值填充 python 字典

[英]Fill a python dictionary with values from a pandas dataFrame

這是我的字典,叫做“評論”:

reviews= {1: {'like', 'the', 'acting'},
          2: {'hate', 'plot', 'story'}}

這是我的“詞典”dataFrame:

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)

詞典

我需要用“詞典”dataFrame 中的負值和正值填充我的“評論”字典。

如果詞典中沒有值,那么我想放 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]}}

lexicon創建字典,然后通過dict.get在雙字典理解映射中創建,如果不匹配則可能添加默認值:

d = lexicon.set_index('word').agg(list, axis=1).to_dict()
print (d)
{'like': [0.0005, 0.0025], 'movie': [0.0014, 0.0019], 'hate': [0.0029, 0.0002]}


out = {k: {x: d.get(x, [0.5,0.5]) for x in v} for k, v in reviews.items()}
print (out)
{1: {'like': [0.0005, 0.0025], 'the': [0.5, 0.5], 'acting': [0.5, 0.5]}, 
 2: {'story': [0.5, 0.5], 'hate': [0.0029, 0.0002], 'plot': [0.5, 0.5]}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM