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. We can create a 1-D array in NumPy using the array() function, which converts a Python list or iterable object.
import numpy as np
# Create a one-dimensional array from a list
array_1d = np.array([1, 2, 3, 4, 5])
print(array_1d)
Output
[1 2 3 4 5]
Let's explore various methods to Create one- dimensional Numpy Array.
Table of Content
Using Arrange()
arrange() returns evenly spaced values within a given interval.
# importing the module
import numpy as np
# creating 1-d array
x = np.arange(3, 10, 2)
print(x)
Output
[3 5 7 9]
Using Linspace()
Linspace() creates evenly space numerical elements between two given limits.
import numpy as np
# creating 1-d array
x = 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.
import numpy as np
# creating the string
str = "geeksforgeeks"
# creating 1-d array
x = 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
import numpy as np
arr5 = 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
import numpy as np
arr6 = np.ones(5)
print(arr6)
Output
[1. 1. 1. 1. 1.]
Using Random() Function
Random() return the random module provides various methods to create arrays filled with random values.
import numpy as np
a=np.random.rand(2,3)
print(a)
Output
[[0.07752187 0.74982957 0.53760007] [0.73647835 0.62539542 0.27565598]]