Numpy Array Initialization (Fill with Identical Values)

NumPy array initialization (fill with identical values)

NumPy 1.8 introduced np.full(), which is a more direct method than empty() followed by fill() for creating an array filled with a certain value:

>>> np.full((3, 5), 7)
array([[ 7., 7., 7., 7., 7.],
[ 7., 7., 7., 7., 7.],
[ 7., 7., 7., 7., 7.]])

>>> np.full((3, 5), 7, dtype=int)
array([[7, 7, 7, 7, 7],
[7, 7, 7, 7, 7],
[7, 7, 7, 7, 7]])

This is arguably the way of creating an array filled with certain values, because it explicitly describes what is being achieved (and it can in principle be very efficient since it performs a very specific task).

Fill a numpy array with the same number?

You can use:

a = np.empty(100)
a.fill(9)

or also if you prefer the slicing syntax:

a[...] = 9

np.empty is the same as np.ones, etc. but can be a bit faster since it doesn't initialize the data.

In newer numpy versions (1.8 or later), you also have:

np.full(100, 9)

NumPy array initialization with tuple (fill with identical tuples)

You can, with the correct dtype. With 'f,f' you can initialise the array with tuples of floats; see Data type objects (dtype) for more.

np.full((3,2), np.nan, dtype='f,f')

array([[(nan, nan), (nan, nan)],
[(nan, nan), (nan, nan)],
[(nan, nan), (nan, nan)]], dtype=[('f0', '<f4'), ('f1', '<f4')])

Fill specific values of a numpy array (master) with values from another numpy array (slave) from same index position

Use:

result = np.where(master == -1, slave, master)

Fill diagonal in 3D numpy array

try this:

r = np.arange(4)
arr[:, r, r] = 1

Example:

arr = np.arange(3*4*4).reshape(3,4,4)
r = np.arange(4)
arr[:, r, r] = 1

output:

array([[[ 1,  1,  2,  3],
[ 4, 1, 6, 7],
[ 8, 9, 1, 11],
[12, 13, 14, 1]],

[[ 1, 17, 18, 19],
[20, 1, 22, 23],
[24, 25, 1, 27],
[28, 29, 30, 1]],

[[ 1, 33, 34, 35],
[36, 1, 38, 39],
[40, 41, 1, 43],
[44, 45, 46, 1]]])

create a numpy array of zeros with same dtype as another array but different shape

NumPy array's have a attribute called dtype. Simply use this attribute when creating a new array with the same data type.

a = np.array([0,1,2])
print(a.dtype) # dtype('int64')
b = np.array([3.1,4.1,5.1], dtype=a.dtype)
print(b) # array([3, 4, 5])


Related Topics



Leave a reply



Submit