Dengan Python, bagaimana cara membuat array numpy dengan bentuk acak yang diisi dengan semua Benar atau semua Salah?
numpy sudah memungkinkan pembuatan array semua atau semua nol dengan sangat mudah:
misalnya numpy.ones((2, 2)) atau numpy.zeros((2, 2))
Karena True dan False diwakili dalam Python sebagai 1 dan 0, masing-masing, kita hanya perlu menentukan array ini harus boolean menggunakan parameter dtype opsional dan kita selesai.
numpy.ones((2, 2), dtype=bool)
pengembalian:
array([[ True, True], [ True, True]], dtype=bool)UPDATE: 30 Oktober 2013
Karena numpy versi 1.8 , kita dapat menggunakan full untuk mencapai hasil yang sama dengan sintaks yang lebih jelas menunjukkan maksud kita (seperti yang ditunjukkan fmonegaglia):
numpy.full((2, 2), True, dtype=bool)
UPDATE: 16 Januari 2017
Karena setidaknya numpy versi 1.12 , full secara otomatis memberikan hasil ke dtype pada parameter kedua, jadi kita bisa menulis:
numpy.full((2, 2), True)
numpy.full((2,2), True, dtype=bool)
ones dan zeros, yang masing-masing membuat array penuh dengan nol dan nol, mengambil parameter dtype opsional:
>>> numpy.ones((2, 2), dtype=bool) array([[ True, True], [ True, True]], dtype=bool) >>> numpy.zeros((2, 2), dtype=bool) array([[False, False], [False, False]], dtype=bool)Jika tidak harus dapat ditulisi, Anda dapat membuat array dengan np.broadcast_to :
>>> import numpy as np >>> np.broadcast_to(True, (2, 5)) array([[ True, True, True, True, True], [ True, True, True, True, True]], dtype=bool)Jika Anda membutuhkannya dapat ditulisi, Anda juga dapat membuat array kosong dan fillNAME _ sendiri:
>>> arr = np.empty((2, 5), dtype=bool) >>> arr.fill(1) >>> arr array([[ True, True, True, True, True], [ True, True, True, True, True]], dtype=bool)Pendekatan-pendekatan ini hanyalah saran alternatif. Secara umum Anda harus tetap menggunakan np.full, np.zeros atau np.ones seperti yang disarankan oleh jawaban lain.
>>> a = numpy.full((2,4), True, dtype=bool) >>> a[1][3] True >>> a array([[ True, True, True, True], [ True, True, True, True]], dtype=bool)
numpy.full (Ukuran, Nilai Skalar, Jenis). Ada juga argumen lain yang dapat diajukan, untuk dokumentasi tentang itu, periksa //docs.scipy.org/doc/numpy/reference/generated/numpy.full.html
Cepat jalankan timeit untuk melihat, jika ada perbedaan antara versi np.full dan np.ones.
Jawab: Tidak
import timeit n_array, n_test = 1000, 10000 setup = f"import numpy as np; n = {n_array};" print(f"np.ones: {timeit.timeit('np.ones((n, n), dtype=bool)', number=n_test, setup=setup)}s") print(f"np.full: {timeit.timeit('np.full((n, n), True)', number=n_test, setup=setup)}s")Hasil:
(penting _
Mengenai pos tentang np.empty (dan saya tidak bisa berkomentar, karena reputasi saya terlalu rendah):
JANGAN MELAKUKANNYA. JANGAN GUNAKAN np.empty untuk menginisialisasi semua -Truearray
Karena array kosong, memori tidak ditulis dan tidak ada jaminan, apa nilai Anda nantinya, mis.
>>> print(np.empty((4,4), dtype=bool)) [[ True True True True] [ True True True True] [ True True True True] [ True True False False]]Hanya demi menambahkan lebih banyak jawaban, inilah cara lain untuk menghasilkan array boolean bentuk sewenang-wenang. Langkah-langkahnya sudah jelas.
# desired shape In [42]: shape = (2, 3) In [43]: true_arr = np.empty(shape, dtype=np.bool) # when needed an array with `False`y values, just negate the `True`thy values In [44]: false_arr = ~np.empty(shape, dtype=np.bool) In [45]: true_arr Out[45]: array([[ True, True, True], [ True, True, True]], dtype=bool) In [46]: false_arr Out[46]: array([[False, False, False], [False, False, False]], dtype=bool)Return a new array of given shape and type, filled with ones.
Parameters shapeint or sequence of intsShape of the new array, e.g., (2, 3) or 2.
dtypedata-type, optionalThe desired data-type for the array, e.g., numpy.int8. Default is numpy.float64.
order{‘C’, ‘F’}, optional, default: CWhether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory.
likearray_like, optionalReference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.
New in version 1.20.0.
ReturnsoutndarrayArray of ones with the given shape, dtype, and order.
See also
ones_likeReturn an array of ones with shape and type of input.
emptyReturn a new uninitialized array.
zerosReturn a new array setting values to zero.
fullReturn a new array of given shape filled with value.
Examples
>>> np.ones(5) array([1., 1., 1., 1., 1.])
>>> np.ones((5,), dtype=int) array([1, 1, 1, 1, 1])
>>> np.ones((2, 1)) array([[1.], [1.]])
>>> s = (2,2) >>> np.ones(s) array([[1., 1.], [1., 1.]])