Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
numpy.arange() in Python
Next article icon

Numpy Arrays are grid-like structures similar to lists inPython but optimized for numerical operations. The most straightforward way to create a NumPy array is by converting a regular Python list into an array using the np.array() function.

Let's understand this with the help of an example:

Python
importnumpyasnp# One-dimensional arrayarr1=np.array([1,2,3,4,5])print(arr1)# Two-dimensional arrayarr2=np.array([[1,2],[3,4]])print(arr2)

Output
[1 2 3 4 5][[1 2] [3 4]]

Creating Arrays with Specific Values

For assigning a specific values. NumPy provides several function to create arrays filled with zeros, ones, or a specific constant value.

  • Zeros Array:np.zeros() function creates an array filled with zeros. It requires the shape of the array as a parameter.

Example:

Python
importnumpyasnp# 3x4 array filled with zerosarr_zero=np.zeros((3,4))print(arr_zero)

Output
[[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]]
  • Ones Array:np.ones() creates an array filled with ones.

Example:

Python
importnumpyasnp# 2x3 array filled with onesarr_one=np.ones((2,3))print(arr_one)

Output
[[1. 1. 1.] [1. 1. 1.]]
  • Full Array :np.full() function allows you to create an array filled with a specific value.

Example:

Python
importnumpyasnp# 2x2 array filled with 7arr_full=np.full((2,2),7)print(arr_full)

Output
[[7 7] [7 7]]

Creating Arrays with Random Values

NumPy also has functions for generating arrays with random values, useful for simulations and testing.

  • Random Float Array :np.random.rand() function generates an array of random values between 0 and 1.

Example:

Python
importnumpyasnp# 2x3 array of random floatsarr_rand=np.random.rand(2,3)print(arr_rand)

Output
[[0.67820861 0.64484802 0.48673431] [0.00263043 0.55383721 0.43240166]]
  • Random Integers :If we need random integers, we can usenp.random.randint() to create arrays with integer values in a specified range.

Example:

Python
importnumpyasnp# 3x3 array of random integers from 1 to 9arr_int=np.random.randint(1,10,size=(3,3))print(arr_int)

Output
[[4 6 5] [7 4 8] [8 5 2]]

Creating Arrays with a Range of Values

Another common method of creating arrays is using a range of values. NumPy provides functions like np.arange() and np.linspace() for this purpose.

  • Using np.arange() :np.arange() creates arrays with values spaced according to a given interval. It’s similar to Python’s built-in range() but returns a NumPy array.

Example:

Python
importnumpyasnp# Array from 0 to 10 with step 2arr_range=np.arange(0,10,2)print(arr_range)

Output
[0 2 4 6 8]
  • Using np.linspace():np.linspace()generates an array with a specified number of evenly spaced values over a specified range.

Example:

Python
importnumpyasnp# 5 values from 0 to 1arr_linspace=np.linspace(0,1,5)print(arr_linspace)

Output
[0.   0.25 0.5  0.75 1.  ]

Identity and Diagonal Matrices

NumPy also provides functions for creating identity matrices and diagonal matrices, which are often used in linear algebra.

  • Identity Matrix :np.eye() function creates an identity matrix, a square matrix with ones on the diagonal and zeros elsewhere.

Example:

Python
importnumpyasnp# 3x3 identity matrixidentity_matrix=np.eye(3)print(identity_matrix)

Output
[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]
  • Diagonal Matrix :Usenp.diag() to create a diagonal matrix, where the provided array elements form the diagonal.

Example:

Python
importnumpyasnp# Diagonal matrix with [1, 2, 3] on the diagonaldiag_matrix=np.diag([1,2,3])print(diag_matrix)

Output
[[1 0 0] [0 2 0] [0 0 3]]

Methods for array creation in Numpy

FunctionDescription
empty()Return a new array of given shape and type, without initializing entries
empty_like()Return a new array with the same shape and type as a given array
eye()Return a 2-D array with ones on the diagonal and zeros elsewhere.
identity()Return the identity array
ones()Return a new array of given shape and type, filled with ones
ones_like()Return an array of ones with the same shape and type as a given array
zeros()Return a new array of given shape and type, filled with zeros
zeros_like()Return an array of zeros with the same shape and type as a given array
full_like()Return a full array with the same shape and type as a given array.
array()Create an array
asarray()Convert the input to an array
asanyarray()Convert the input to an ndarray, but pass ndarray subclasses through
ascontiguousarray()Return a contiguous array in memory (C order)
asmatrix()Interpret the input as a matrix
copy()Return an array copy of the given object
frombuffer()Interpret a buffer as a 1-dimensional array
fromfile()Construct an array from data in a text or binary file
fromfunction()Construct an array by executing a function over each coordinate
fromiter()Create a new 1-dimensional array from an iterable object
fromstring()A new 1-D array initialized from text data in a string
loadtxt()Load data from a text file
arange()Return evenly spaced values within a given interval
linspace()Return evenly spaced numbers over a specified interval
logspace()Return numbers spaced evenly on a log scale
geomspace()Return numbers spaced evenly on a log scale (a geometric progression)
meshgrid()Return coordinate matrices from coordinate vectors
mgrid()nd_grid instance which returns a dense multi-dimensional “meshgrid
ogrid()nd_grid instance which returns an open multi-dimensional “meshgrid
diag()Extract a diagonal or construct a diagonal array
diagflat()Create a two-dimensional array with the flattened input as a diagonal
tri()An array with ones at and below the given diagonal and zeros elsewhere
tril()Lower triangle of an array
triu()Upper triangle of an array
vander()Generate a Vandermonde matrix
mat()Interpret the input as a matrix
bmat()Build a matrix object from a string, nested sequence, or array

Improve
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp