Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何计算元素在数组中特定位置出现的次数?_Python_Arrays_Matrix_Bigdata - Fatal编程技术网

Python 如何计算元素在数组中特定位置出现的次数?

Python 如何计算元素在数组中特定位置出现的次数?,python,arrays,matrix,bigdata,Python,Arrays,Matrix,Bigdata,我有大量的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和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个特性,用于朴素贝叶斯分类器的实现。

求和的想法也可以,但我有一个想法,即先转置列表,然后运行集合。每行计数器

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处有一个零和两个一

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}

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

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))
打印(结果)


如果您将数组(列表?)组织成一个2D numpy数组,比如说,
xy
,那么解决方案将非常简单,
xy.sum(axis=0)
。sum会给我零和一的数目吗?在每个位置?0和1的总和定义为1的数量。数组是如何存储的?数组存储为列表。
[(1, 2), (2, 1), (1, 2), (0, 3)] #a dummy result