Creating a onedimensional NumPy array (original) (raw)

Creating a one-dimensional NumPy array

Last Updated : 27 Jan, 2025

**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.

Python `

import numpy as np

Create a one-dimensional array from a list

array_1d = np.array([1, 2, 3, 4, 5]) print(array_1d)

`

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.

Python `

importing the module

import numpy as np

creating 1-d array

x = np.arange(3, 10, 2) print(x)

`

Using L**inspace()

L**inspace()creates evenly space numerical elements between two given limits.

Python `

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.

Python `

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

Python `

import numpy as np

arr5 = np.zeros(5) print(arr5)

`

**Output:

[0.0.0.0.0]

U**sing Ones() Function

**ones()returns the numbers of 1s as passed in the parameter of the method

Python `

import numpy as np

arr6 = np.ones(5) print(arr6)

`

**Using Random() Function

**Random() return the random module provides various methods to create arrays filled with random values.

Python `

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]]

Similar Reads

Introduction



















NumPy Array Manipulation


















Matrix in NumPy


















Operations on NumPy Array




Reshaping NumPy Array















Indexing NumPy Array






Arithmetic operations on NumPyArray










Linear Algebra in NumPy Array