Python- numpy數組初始化為相同的值


有時我們需要將numpy數組初始化為相同的值,numpy提供了一些方法幫助我們實現這個目的。

很多人學習python,不知道從何學起。

很多人學習python,掌握了基本語法過后,不知道在哪里尋找案例上手。

很多已經做案例的人,卻不知道如何去學習更加高深的知識。

那么針對這三類人,我給大家提供一個好的學習平台,免費領取視頻教程,電子書籍,以及課程的源代碼!??¤

QQ群:1057034340

1. np.zeros

np.zeros返回來一個給定形狀和類型的用0填充的數組。

numpy.zeros(shape, dtype=float, order='C')
np.zeros(5)
array([ 0., 0., 0., 0., 0.]) np.zeros((5,), dtype=int) array([0, 0, 0, 0, 0]) np.zeros((2, 1)) array([[ 0.], [ 0.]]) np.zeros((2, 2)) array([[ 0., 0.], [ 0., 0.]])

2. np.ones

np.ones返回來一個給定形狀和類型的用1填充的數組。

numpy.ones(shape, dtype=None, order='C')
>>> 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.]])

初始化數組中的所有元素為10:

>>> import numpy as np
>>> a = np.ones((4,4)) * 10 [[10. 10. 10. 10.] [10. 10. 10. 10.] [10. 10. 10. 10.] [10. 10. 10. 10.]]

3. np.full

np.full返回來一個給定形狀和類型的用fill_value填充的數組。

numpy.full(shape, fill_value, dtype=None, order='C')
>>> np.full((3, 5), 7, dtype=int) array([[7, 7, 7, 7, 7], [7, 7, 7, 7, 7], [7, 7, 7, 7, 7]]) >>> np.full((2, 2), np.inf) array([[inf, inf], [inf, inf]]) >>> np.full((2, 2), [1, 2]) array([[1, 2], [1, 2]])

4. 數組填充-fill

np.empty 方法用來創建一個指定形狀(shape)、數據類型(dtype)且未初始化的數組。

numpy.empty(shape, dtype=float, order='C')

np.empy生成的數組元素為隨機值。

>>> np.empty([2, 2]) array([[ -9.74499359e+001, 6.69583040e-309], [ 2.13182611e-314, 3.06959433e-309]]) #uninitialized >>> np.empty([2, 2], dtype=int) array([[-1073741821, -1067949133], [ 496041986, 19249760]]) #uninitialized
>>> a = np.empty([2, 2]) >>> a.fill(20) [[20. 20.] [20. 20.]] >>> a[:] = 30 [[30. 30.] [30. 30.]]

5. np.repeat

np.repeat實現重復數組元素的功能。

numpy.repeat(a, repeats, axis=None)[source]
>>> np.repeat(3, 4) array([3, 3, 3, 3]) >>> x = np.array([[1,2],[3,4]]) >>> np.repeat(x, 2) array([1, 1, 2, 2, 3, 3, 4, 4]) >>> np.repeat(x, 3, axis = 1) array([[1, 1, 1, 2, 2, 2], [3, 3, 3, 4, 4, 4]]) >>> np.repeat(x, [1, 2], axis = 0) array([[1, 2], [3, 4], [3, 4]])

6. np.tile

np.tile把數組沿各個方向復制。

numpy.tile(A, reps)
>>> a = np.array([0, 1, 2]) >>> np.tile(a, 2) array([0, 1, 2, 0, 1, 2]) >>> np.tile(a, (2, 2)) array([[0, 1, 2, 0, 1, 2], [0, 1, 2, 0, 1, 2]]) >>> np.tile(a, (2, 1, 2)) array([[[0, 1, 2, 0, 1, 2]], [[0, 1, 2, 0, 1, 2]]]) >>> b = np.array([[1, 2], [3, 4]]) >>> np.tile(b, 2) array([[1, 2, 1, 2], [3, 4, 3, 4]]) >>> np.tile(b, (2, 1)) array([[1, 2], [3, 4], [1, 2], [3, 4]]) >>> c = np.array([1,2,3,4]) >>> np.tile(c,(4,1)) array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]])


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM