【问题标题】:How can I count the number of times an element occurs in a specific position in an array? [closed]如何计算元素在数组中特定位置出现的次数? [关闭]
【发布时间】:2017-05-01 02:23:08
【问题描述】:

我有大量的 0 和 1 数组,就像这样 - 每个数组的数组长度为 812。

    a = [1, 0, 0, 1, 0,....]
    b = [0, 1, 0, 0, 1,....]
    .
    .
    .
    x = [0, 1, 0,..........]

我想做的是计算 1 和 0 出现在第一个、第二个、...第 812 个位置的次数。任何想法或想法表示赞赏。 我想要的是一个像这样的数组: array = [(32,56), (78,89)....] 元组的第一个元素在第一个位置(索引)处给出 1 的数量,第二个元素给出 0 的数量。这些数组用于存储朴素贝叶斯分类器实现的 812 个特征。

【问题讨论】:

  • 如果您将数组(列表?)组织成一个二维 numpy 数组,例如 xy,则解决方案将像 xy.sum(axis=0) 一样简单。
  • 总和会给我零和一的数量吗?在每个位置?
  • 0 和 1 的和根据定义是 1 的个数。
  • 数组是如何存储的?
  • 数组存储为列表。

标签: python arrays matrix bigdata


【解决方案1】:

求和的想法也可以,但我有转置列表然后为每一行运行 collections.Counter 的想法

import numpy as np
import collections

nums = [
    [1, 0, 0, 1, 0],
    [0, 1, 0, 0, 1],
    [0, 1, 0, 1, 1]
]

np_nums = np.array(nums)
transposed = np.transpose(np_nums)
for i, row in enumerate(transposed):
    print("Index {} {}".format(i, dict(collections.Counter(row))))

这个输出:

Index 0 {1: 1, 0: 2}
Index 1 {0: 1, 1: 2}
Index 2 {0: 3}
Index 3 {1: 2, 0: 1}
Index 4 {0: 1, 1: 2}

这意味着在索引 0 处有一个 1 和两个零,在索引 1 处有一个零和两个 1

【讨论】:

    【解决方案2】:

    这是我根据你的问题理解的

    def arrayCount(arrays, index):
        data = {}
        for x in arrays:
            if data.get(x[index]) is None:
                data[x[index]] = 1
            else:
                data[x[index]] += 1
        return data
    
    
    a = [1, 0, 0, 1, 0]
    b = [0, 1, 0, 0, 1]
    x = [0, 1, 0, 1, 1]
    y = [0, 1, 0, 1, 1]
    z = [0, 2, 0, 1, 1]
    
    arrays = [a, b, x, y, z]
    print arrayCount(arrays, 1)
    
    '''OUTPUT'''
    # {0: 1, 1: 3, 2: 1}
    

    【讨论】:

      【解决方案3】:

      这里我提供了一个通用的解决方案(你可以将它用于数组中的任何值,包括 0 和 1)。将所有列表合并到 numpy nd-array,因为所有列表的长度都相同

      import numpy as np
      concat_array = np.concatenate((a,b,c,...x), axis=0)
      

      沿轴=0(按列)查找值的出现次数并组合形成一个元组

      # use loop if have more unique values
      n_ones = (concat_array = 1).sum(axis=0)
      n_zeros = (concat_array = 0).sum(axis=0)
      #zip it to form a tuple
      result = list(zip(n_ones, n_zeros))
      

      打印(结果)

      [(1, 2), (2, 1), (1, 2), (0, 3)] #a dummy result
      

      【讨论】:

        猜你喜欢
        • 2015-08-22
        • 2017-12-05
        • 1970-01-01
        • 2021-12-09
        • 2022-11-30
        • 2015-08-13
        • 1970-01-01
        • 2014-09-30
        • 1970-01-01
        相关资源
        最近更新 更多