One-dimensional arraycontains elements only in one dimension. In other words, the shape of theNumPy array should contain only one value in the tuple. We can create a 1-D array in NumPy using the array() function, which converts a Python list or iterable object.
Pythonimportnumpyasnp# Create a one-dimensional array from a listarray_1d=np.array([1,2,3,4,5])print(array_1d)
Let's explore various methods to Create one- dimensional Numpy Array.
UsingArrange()
arrange()returns evenly spaced values within a given interval.
Python# importing the moduleimportnumpyasnp# creating 1-d arrayx=np.arange(3,10,2)print(x)
Using Linspace()
Linspace()creates evenly space numerical elements between two given limits.
Pythonimportnumpyasnp# creating 1-d arrayx=np.linspace(3,10,3)print(x)
Output:
[ 3. 6.5 10. ]
Using Fromiter()
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.
Pythonimportnumpyasnp# 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']
Using Zeros()
Zeros()returns the numbers of 0s as passed in the parameter of the method
Pythonimportnumpyasnparr5=np.zeros(5)print(arr5)
Output:
[0.0.0.0.0]
Using Ones() Function
ones()returns the numbers of 1s as passed in the parameter of the method
Pythonimportnumpyasnparr6=np.ones(5)print(arr6)
Using Random() Function
Random()return the random module provides various methods to create arrays filled with random values.
Pythonimportnumpyasnpa=np.random.rand(2,3)print(a)
Output[[0.07752187 0.74982957 0.53760007] [0.73647835 0.62539542 0.27565598]]