
mfloww
In Python habe ich ein ndarray y
das ist gedruckt als array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
Ich versuche zu zählen, wie viele 0
s und wie viele 1
s gibt es in diesem Array.
Aber wenn ich tippe y.count(0)
oder y.count(1)
es sagt
numpy.ndarray
Objekt hat kein Attribut count
Was sollte ich tun?

Özgür Vatansever
a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
unique, counts = numpy.unique(a, return_counts=True)
dict(zip(unique, counts))
# {0: 7, 1: 4, 2: 1, 3: 2, 4: 1}
Non-numpy Weg:
Benutzen collections.Counter
;
import collections, numpy
a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
collections.Counter(a)
# Counter({0: 7, 1: 4, 3: 2, 2: 1, 4: 1})
Ich persönlich würde zu:
(y == 0).sum()
und (y == 1).sum()
Z.B
import numpy as np
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
num_zeros = (y == 0).sum()
num_ones = (y == 1).sum()

Ibrahim Berber
Filtern und verwenden len
Verwenden len
könnte eine weitere Option sein.
A = np.array([1,0,1,0,1,0,1])
Angenommen, wir möchten die Anzahl der Vorkommen von 0
.
A[A==0] # Return the array where item is 0, array([0, 0, 0])
Wickeln Sie es jetzt mit ein len
.
len(A[A==0]) # 3
len(A[A==1]) # 4
len(A[A==7]) # 0, because there isn't such item.

Akavall
Für Ihren Fall könnten Sie auch nachsehen numpy.bincount
In [56]: a = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
In [57]: np.bincount(a)
Out[57]: array([8, 4]) #count of zeros is at index 0 : 8
#count of ones is at index 1 : 4
10063200cookie-checkWie kann man das Auftreten bestimmter Elemente in einem Ndarray zählen?yes
In diesem Fall ist es auch möglich, einfach zu verwenden
numpy.count_nonzero
.– Mong H.Ng
31. März 2019 um 17:50 Uhr