【问题标题】:Loop through pandas columns and append a dict of sets?循环遍历熊猫列并附加集合的字典?
【发布时间】:2021-03-13 23:13:53
【问题描述】:

我希望在 pandas 数据框中循环遍历大约 1000 万行,并将它们添加到已经存在的集合字典中。

例如对于这样的字典

x = {10: {1, 2, 3, 5}, 12: {6, 7, 8, 9, 10}}

还有这样的数据框:

d = {'ID': [10, 10, 10, 12, 12, 12], 'Another_ID': [1, 4, 6, 6, 7, 13]}
df = pd.DataFrame(data=d)

ID   Another_ID

10   1
10   4
10   6
12   6
12   7
12   13

我想浏览这些行并添加 ID“尚未看到”的新值。我想要这样的结果。

x = {10: {1, 2, 3, 4, 5, 6}, 12: {6, 7, 8, 9, 10, 13}}

我尝试过使用类似以下的简单函数进行迭代。

for i in df [['ID' , 'Another_ID' ]] .values():
    dict[i[0]].add(i[1])

我可以通过这样说以下内容来手动添加值,但不能循环执行!

  dict[10].add(6)

如果有人知道如何遍历这两个 pandas 列并向集合添加新值,请告诉我!

  • 请记住,这必须相对较快地完成,因为有 1000 万行

谢谢!

【问题讨论】:

    标签: python pandas dictionary set


    【解决方案1】:

    您可以使用 groupbyagg 将 df 转换为与“x”类似的格式:

    x2 = df.groupby('ID')['Another_ID'].agg(set).to_dict()
    print (x2)
    # {10: {1, 4, 6}, 12: {6, 7, 13}}
    

    现在,我们使用一个表达式合并两个字典:

    x3 = {k: x.get(k, set()) | x2.get(k, set()) for k in x}
    print (x3)
    # {10: {1, 2, 3, 4, 5, 6}, 12: {6, 7, 8, 9, 10, 13}}
    

    或者,对于就地合并(如果x 很大而x2 很小,则更有意义):

    for k in x2:
        x[k] = x2[k] | x.get(k, set())
    
    print (x)
    # {10: {1, 2, 3, 4, 5, 6}, 12: {6, 7, 8, 9, 10, 13}}
    

    | 运算符表示两个集合操作数的集合并集。

    【讨论】:

      【解决方案2】:

      您可以将您的数据框视为字典,使用defaultdict 将您的数据从 Pandas 数据框中取出,然后遍历该字典以获得最终输出:

      from collections import defaultdict
      
      dd = defaultdict(list)
      
      for ID, another_ID in zip(df.ID, df.Another_ID):
          dd[ID].append(another_ID)
      
      dd
      
      defaultdict(list, {10: [1, 4, 6], 12: [6, 7, 13]})
      

      最终结果:

      {key: value.union(dd[key]) for key, value in x.items()}
      
      {10: {1, 2, 3, 4, 5, 6}, 12: {6, 7, 8, 9, 10, 13}}
      

      【讨论】:

        【解决方案3】:

        熊猫的一种方式explode

        out = pd.Series(x).map(list).explode().append(df.set_index('ID')['Another_ID']).groupby(level=0).agg(set).to_dict()
        Out[361]: {10: {1, 2, 3, 4, 5, 6}, 12: {6, 7, 8, 9, 10, 13}}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-22
          • 1970-01-01
          • 1970-01-01
          • 2014-09-08
          • 2017-06-08
          • 1970-01-01
          • 2020-11-20
          相关资源
          最近更新 更多