3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

numpy.arraysの和集合・差集合まとめ

Posted at

概要

numpyのarrayを使った和集合と差集合のまとめです。
nunique・appendなどのメソッドや、set型を組み合わせれば、工夫次第で実現できますが、用意された関数が既にあるようなので、それを使ってしまいましょう!

準備

In [1]: import numpy as np

In [2]: array_a = np.array([1, 2, 3, 4, 5])

In [3]: array_b = np.array([1, 3, 5, 7, 9])

和集合(Union)

np.union1d(A, B)は、np.array型の新しい集合A∪B = {x|x∈A 又は x∈B}を返します。

In [4]: np.union1d(array_a, array_b)
Out[4]: array([1, 2, 3, 4, 5, 7, 9])

差集合(Difference set)

np.setdiff1d(A, B)は、np.array型の新しい集合A\B = {x|x∈A かつ x∉B}を返します。

In [5]: np.setdiff1d(array_a, array_b)
Out[5]: array([2, 4])
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?