Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.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 如何计算np数组中出现了多少个数组?_Python_Python 3.x_Python 2.7 - Fatal编程技术网

Python 如何计算np数组中出现了多少个数组?

Python 如何计算np数组中出现了多少个数组?,python,python-3.x,python-2.7,Python,Python 3.x,Python 2.7,假设我有: x = [[0, 1], [0, 1], [0, 2], [0, 2], [0, 3]] 我想有一个类似这样的输出: count = [0, 1] = 2, [0, 2] = 2, [0, 3] = 1 如何计算发生的数组数?使用如下类: 代码: 请注意,由于计数器是dict,因此键需要是可散列的。这就是为什么需要x中i的元组(i),因为这会将x中的列表转换为元组,以便它们可以用作计数器的键 测试代码: 结果: 下面的代码将解决这个问题 print({str(i):x.count

假设我有:

x = [[0, 1], [0, 1], [0, 2], [0, 2], [0, 3]]
我想有一个类似这样的输出:

count = [0, 1] = 2, [0, 2] = 2, [0, 3] = 1
如何计算发生的数组数?

使用如下类:

代码: 请注意,由于
计数器
dict
,因此键需要是可散列的。这就是为什么需要x中i的
元组(i),因为这会将
x
中的列表转换为元组,以便它们可以用作
计数器的键

测试代码: 结果:
下面的代码将解决这个问题

print({str(i):x.count(i) for i in x})

numpy
中,您可以使用
np.unique
,例如:

In []:
np.unique(x, axis=0, return_counts=True)

Out[]:
(array([[0, 1],
        [0, 2],
        [0, 3]]), array([2, 2, 1]))
In []:
list(zip(*np.unique(x, axis=0, return_counts=True)))

Out[]:
[(array([0, 1]), 2), (array([0, 2]), 2), (array([0, 3]), 1)]
如果要折叠它们,则可以使用
zip()
,例如:

In []:
np.unique(x, axis=0, return_counts=True)

Out[]:
(array([[0, 1],
        [0, 2],
        [0, 3]]), array([2, 2, 1]))
In []:
list(zip(*np.unique(x, axis=0, return_counts=True)))

Out[]:
[(array([0, 1]), 2), (array([0, 2]), 2), (array([0, 3]), 1)]

如果您正在寻找纯numpy解决方案:

In [12]: import numpy as np

In [13]: x = np.array([[0, 1], [0, 1], [0, 2], [0, 2], [0, 3]])

In [14]: np.unique(x, axis=0, return_counts=True)
Out[14]: 
(array([[0, 1],
        [0, 2],
        [0, 3]]), array([2, 2, 1]))
您可以尝试:

1。使用
.count

结果

{((0, 1), 2), ((0, 2), 2), ((0, 3), 1)}
{(0, 1): 2, (0, 3): 1, (0, 2): 2}
[((0, 1), 2), ((0, 3), 1), ((0, 2), 2)]

2。使用
defaultdict

结果

{((0, 1), 2), ((0, 2), 2), ((0, 3), 1)}
{(0, 1): 2, (0, 3): 1, (0, 2): 2}
[((0, 1), 2), ((0, 3), 1), ((0, 2), 2)]

3。使用
计数器

结果

{((0, 1), 2), ((0, 2), 2), ((0, 3), 1)}
{(0, 1): 2, (0, 3): 1, (0, 2): 2}
[((0, 1), 2), ((0, 3), 1), ((0, 2), 2)]

我运行了这个程序,在Python2.7和Python3.5中都得到了
[2,2,2,1]
。这给出了每个元素的计数,但这不是OP想要的。OP正在寻找
count=[0,1]=2[0,2]=2[0,3]=1
或类似的东西。现在它输出
[([0,1],2),([0,1],2),([0,2],2),([0,3],1)]
。仍然不是OP想要的。为什么
str(i)
?为什么不仅仅是
i
?numpy在哪里?到目前为止你做了什么尝试或研究?你可能想提到为什么
计数器
指令
意味着你不能只做
计数器(x)
+不管怎样,这太棒了!但是如何选择仅在计数>c的位置打印?因此,当我设置c=1时,(0,3):1不打印
计数器(如果i[1]>c,则i表示计数中的i)
其中
计数=计数器(tuple(i)表示x中的i)