Creating a one-dimensional NumPy array
One dimensional array contains elements only in one dimension. In other words, the shape of the NumPy array should contain only one value in the tuple. Let us see how to create 1 dimensional NumPy arrays.
Method 1: First make a list then pass it in numpy.array()
Python3
# importing the moduleimport numpy as np# creating the listlist = [100, 200, 300, 400]# creating 1-d arrayn = np.array(list)print(n) |
Output:
[100 200 300 400]
Method 2: .fromiter() is useful for creating non-numeric sequence type array however it can create any type of array. Here we will convert a string into a NumPy array of characters.
Python3
# importing the moduleimport numpy as np# creating the stringstr = "geeksforgeeks"# creating 1-d arrayx = np.fromiter(str, dtype = 'U2')print(x) |
Output:
['g' 'e' 'e' 'k' 's' 'f' 'o' 'r' 'g' 'e' 'e' 'k' 's']
Method 3: .arange() returns evenly spaced values within a given interval.
Python3
# importing the moduleimport numpy as np# creating 1-d arrayx = np.arange(3, 10, 2)print(x) |
Output:
[3 5 7 9]
Method 4: .linspace() creates evenly space numerical elements between two given limits.
Python3
# importing the moduleimport numpy as np# creating 1-d arrayx = np.linspace(3, 10, 3)print(x) |
Output:
[ 3. 6.5 10. ]
Method 5: .zeros() returns the numbers of 0s as passed in the parameter of the method
Python3
import numpy as nparr5 = np.zeros(5)print(arr5) |
Output:
[0. 0. 0. 0. 0.]
Method 6: .ones() returns the numbers of 1s as passed in the parameter of the method
Python3
import numpy as nparr6 = np.ones(5)print(arr6) |
Output:
[1. 1. 1. 1. 1.]



Please Login to comment...