📜  Python中的numpy.full_like(1)

📅  最后修改于: 2023-12-03 15:34:25.333000             🧑  作者: Mango

Numpy.full_like in Python

Introduction

Numpy is a powerful Python library that provides functions for performing complex mathematical operations on arrays and matrices. Among the many functions that numpy provides, numpy.full_like is a unique one that allows you to create a new array with the same shape and type as an existing one, with all its elements filled with a constant value.

Syntax

The syntax for using numpy.full_like is:

numpy.full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None)

Parameters

  • a : The array to use as a template. The shape and type of this array will be used to create the new array.
  • fill_value : The value to fill the new array with.
  • dtype : The data type of the new array. If None, the data type of a will be used.
  • order : Specify the memory layout of the new array to be created.
  • subok : If True, the new array will be an array subclass of a, otherwise it will be a plain numpy array.
  • shape : If specified, the shape of the new array will be determined by this parameter. If not specified, the shape of a will be used.

Example

import numpy as np

a = np.array([[1, 2], [3, 4]])
b = np.full_like(a, 5)

print("a: \n", a)
print("b: \n", b)

Output:

a: 
 [[1 2]
  [3 4]]
b: 
 [[5 5]
  [5 5]]

In the above example, we create an array a with shape (2, 2) and type int64. We then use numpy.full_like to create a new array b with the same shape and type as a, and fill it with the value 5. The resulting b array has the same shape and type as a, but with all its elements set to 5.

Conclusion

In this tutorial, we learned about the numpy.full_like function in Python. We saw how it can be used to create a new array with the same shape and type as an existing one, but with all its elements filled with a constant value. This function is particularly useful in situations where you need to initialize an array with a specific value before performing operations on it.