ホームページ  >  記事  >  バックエンド開発  >  NumPy 配列内の要素の出現をカウントするにはどうすればよいですか?

NumPy 配列内の要素の出現をカウントするにはどうすればよいですか?

Barbara Streisand
Barbara Streisandオリジナル
2024-10-20 21:50:30830ブラウズ

How to Count Occurrences of Elements in NumPy Arrays?

NumPy 配列の出現回数をカウントする

NumPy 配列は数値計算に広く使用されており、一般的なタスクは特定の要素の出現回数をカウントすることです。彼らの中で。ただし、リストや他の Python データ構造とは異なり、NumPy 配列には組み込みの count メソッドがありません。

NumPy の独自の関数を使用する

numpy.unique 関数は次のようにすることができます。配列内の固有の値とそのそれぞれの数を決定するために使用されます。オプションのパラメータ return_counts を受け取ります。これを True に設定すると、一意の値とそれに対応するカウントの両方が返されます。例:

<code class="python">import numpy

# Create a NumPy array
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])

# Obtain unique values and their counts
unique, counts = numpy.unique(y, return_counts=True)

# Convert the results to a dictionary for ease of access
results = dict(zip(unique, counts))

print(results)  # Output: {0: 7, 1: 4}</code>

NumPy 以外のメソッド: collections.Counter の使用

または、NumPy の外部から collections.Counter クラスを使用できます。このクラスは、NumPy 配列を含む任意の反復可能オブジェクトの出現回数をカウントするために特別に設計されています:

<code class="python">import collections

# Use the Counter class to tally the occurrences of each element
counter = collections.Counter(y)

# Print the Counter object to view the occurrences
print(counter)  # Output: Counter({0: 7, 1: 4})</code>

以上がNumPy 配列内の要素の出現をカウントするにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。