Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
NumPy - linspace() Function
Next article icon

To create anarray filled with all ones, given the shape and type of array, we can usenumpy.ones() methodof NumPy library in Python.

Python
importnumpyasnparray=np.ones(5)print(array)

Output:

[1. 1. 1. 1. 1.]

2D Array of Ones

We can also create a 2D array (matrix) filled with ones by passing a tupleto the shape parameter.

Python
importnumpyasnp# Create a 2D array of ones (3 rows, 4 columns)ones_array_2d=np.ones((3,4))print(ones_array_2d)

Output
[[1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]]

Array with a Specific Data Type

We can specify the data type of the array using thedtype parameter.

Python
importnumpyasnp# Create an integer array of ones with 4 elementsones_int_array=np.ones(4,dtype=int)print(ones_int_array)

Output
[1 1 1 1]

Explanation:

  • By specifying dtype=int,we ensure that the array is of integer type instead of thedefault float64.

Multi-Dimensional Array of Ones

We can also create a higher-dimensional array (3D or more) by passing a tuple representing the shape.

Python
importnumpyasnp# Create a 3D array of ones with shape (2, 3, 4)ones_array_3d=np.ones((2,3,4))print(ones_array_3d)

Output
[[[1. 1. 1. 1.]  [1. 1. 1. 1.]  [1. 1. 1. 1.]] [[1. 1. 1. 1.]  [1. 1. 1. 1.]  [1. 1. 1. 1.]]]

Improve

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