【问题标题】:How to get same rows index in a list?如何在列表中获取相同的行索引?
【发布时间】:2019-01-17 07:19:43
【问题描述】:

我有一个这样的 numpy 数组:

[[0 1 0]
 [1 2 1]
 [2 2 1]
 [3 0 0]
 [4 0 1]
 [5 1 2]
 [6 0 1]
 [7 1 0]
 [8 1 2]]

第一列是索引,其他两列是位置 x,y。

我想获取具有相同 x,y 位置的索引列表。

例如对于上述输入,输出可以是每一行中的一组索引:

groups = [[0,7],
          [1,2],
          [4,6],
          [5,8],
          [3]]

所以每一行代表一组具有相同位置 x,y 的索引。 5 个组,其中 4 个组有 2 个成员,而请注意最后一行仅显示索引 3。该组只有一个索引,即 3。

如何在 python 中实现这一点?

【问题讨论】:

    标签: python numpy duplicates


    【解决方案1】:

    看看这个:

    lis = [[0 ,1, 0],
     [1, 2, 1],
     [2, 2, 1],
     [3, 0, 0],
     [4, 0, 1],
     [5, 1, 2],
     [6, 0, 1],
     [7, 1, 0],
     [8, 1, 2]]
    
    dic = {}
    
    for x,y,z in lis:
        if dic.get((y,z)):
            dic[(y,z)].append(x)
        else:
            dic[(y, z)] = [x]
    final_list = [dic[key] for key in dic.keys()]
    
    print(final_list)
    

    【讨论】:

    • 太棒了!像魅力一样工作。刚刚将我的 numpy 数组转换为列表并使用了您的建议。谢谢。
    【解决方案2】:

    您似乎想要按操作分组之类的功能。最好的办法是将其转换为 pandas 数据框,然后进行分组。

    import pandas as pd
    
    a = [[0, 1, 0], [1, 2, 1], [2, 2, 1], 
         [3, 0, 0], [4, 0, 1], [5, 1, 2], 
         [6, 0, 1], [7, 1, 0], [8, 1, 2]]
    
    df = pd.DataFrame(a, columns =['index', 'x', 'y'])
    grouped_df = df.groupby(['x', 'y']).aggregate(lambda x: tuple(x)).reset_index()
    
    print(grouped_df)
    

    输出:

       x  y   index
    0  0  0    (3,)
    1  0  1  (4, 6)
    2  1  0  (0, 7)
    3  1  2  (5, 8)
    4  2  1  (1, 2)
    

    【讨论】:

      【解决方案3】:

      使用collections.defaultdict的其他选项:

      from collections import defaultdict
      
      res = defaultdict(list)
      for x, y, z in array:
        res[(y,z)].append(x)
      

      然后就可以调用了

      print(list(res.values()))
      #=> [[0, 7], [1, 2], [3], [4, 6], [5, 8]]
      

      【讨论】:

        【解决方案4】:

        最简单的方式,不使用任何包;

        l = [[0, 1, 0],
         [1, 2, 1],
         [2, 2, 1],
         [3, 0, 0],
         [4, 0, 1],
         [5, 1, 2],
         [6, 0, 1],
         [7, 1, 0],
         [8, 1, 2]]
        
        s = [(l1[0], l1[1:]) for l1 in l]
        s = [[x for x, y in s if y == b] for a, b in s]
        s = [y for x, y in enumerate(s) if y not in s[:x]]
        print(s)
        

        输出

        [[0, 7], [1, 2], [3], [4, 6], [5, 8]]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-08
          相关资源
          最近更新 更多