【问题标题】:Updating the Key-Value pairs in defaultdict更新 defaultdict 中的键值对
【发布时间】:2018-12-28 06:59:28
【问题描述】:

以上数据框由以下代码生成:

newCols = ['Book-1', 'Book-2', 'Similarity Score']

l1 = ['b1', 'b1', 'b2']
l2 = ['b2', 'b3', 'b3']
score1 = [0.95, 0.87, 0.84]

duplicateProductList = pd.DataFrame(columns=newCols)

duplicateProductList['Book-1'] = l1
duplicateProductList['Book-2'] = l2
duplicateProductList['Similarity Score'] = score1

print(duplicateProductList)

我使用以下代码从 Pandas Dataframe(duplicateProductList (如上所示)) 生成了一个字典:

from collections import defaultdict    

new_dict = {}

my_list = [(i,[a,b]) for i, a,b in zip(duplicateProductList['Book-1'], duplicateProductList['Book-2'], duplicateProductList['Similarity Score'])]
for (key, value) in my_list:
    if key in new_dict:
        new_dict[key].append(value)
    else:
        new_dict[key] = [value]

print(new_dict)

上面的代码 sn-p 产生以下字典:

{'b1':[['b2', 0.95], ['b3', 0.87]], 'b2':[['b3', 0.84]]}

相反,我想生成以下字典:

{'b1':[['b2', 0.95], ['b3', 0.87]], 'b2':[['b1', 0.95],['b3', 0.84]], 'b3':[['b1', 0.87],['b2', 0.84]]}

有人可以帮助我修改字典理解以生成上述字典吗?

【问题讨论】:

标签: python python-3.x pandas collections defaultdict


【解决方案1】:
>>> import collections
>>> from pprint import pprint

>>> df
  Book-1 Book-2  Similarity Score
0     b1     b2              0.95
1     b1     b3              0.87
2     b2     b3              0.84
>>> 
>>> d = collections.defaultdict(list)
>>> for row in df.itertuples(index=False):
    a,b,c = row
    d[a].append((b,c))
    d[b].append((a,c))


>>> pprint(d)
defaultdict(<class 'list'>,
            {'b1': [('b2', 0.95), ('b3', 0.87)],
             'b2': [('b1', 0.95), ('b3', 0.84)],
             'b3': [('b1', 0.87), ('b2', 0.84)]})

【讨论】:

  • 这是一个很棒的解决方案,我非常期待。我正在考虑构建一个相似度矩阵,然后将所有元素作为键值对写入我的字典中(但这会产生可伸缩性问题)。感谢这个优雅的实现!
  • 我没有想太多,可能有 Pandas 的方法可以从 DataFrame 中梳理出这些关系。
猜你喜欢
  • 1970-01-01
  • 2020-05-02
  • 2016-10-04
  • 2015-05-13
  • 1970-01-01
  • 2013-02-03
  • 1970-01-01
  • 2021-12-02
  • 2016-10-11
相关资源
最近更新 更多