w3resource

NumPy: Convert a list of numeric value into a one-dimensional NumPy array


Convert List to 1D Array

Write a NumPy program to convert a list of numeric values into a one-dimensional NumPy array.

Python NumPy: Convert a list of numeric value into a one-dimensional NumPy array

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a Python list 'l' containing floating-point numbers
l = [12.23, 13.32, 100, 36.32]

# Printing the original Python list
print("Original List:", l)

# Creating a NumPy array 'a' from the Python list 'l'
a = np.array(l)

# Printing the one-dimensional NumPy array 'a'
print("One-dimensional NumPy array: ", a)

Sample Output:

Original List: [12.23, 13.32, 100, 36.32]                               
One-dimensional NumPy array:  [  12.23   13.32  100.     36.32]

Explanation:

In the above code -

The above code converts a Python list of floating-point numbers into a one-dimensional NumPy array and prints the result.

numpy.array: Create an array.

Syntax: numpy.array(object, dtype=None, copy=True, order=’K’, subok=False, ndmin=0)

Parameters:

Name Description Required / Optional
object An array, any object exposing the array interface. Required
dtype : data-type, optional The desired data-type for the array. Optional
copy (bool) If true (default), then the object is copied. Optional
order : 'K', 'A', 'C', 'F' Specify the memory layout of the array. If object is not an array, the newly created array will be in C order (row major) unless ‘F’ is specified, in which case it will be in Fortran order. Optional
subok (bool) If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array. Optional
ndmin (int) Specifies the minimum number of dimensions that the resulting array should have. Optional

For more Practice: Solve these Related Problems:

  • Convert a nested list of numbers into a flat one-dimensional NumPy array using vectorized methods.
  • Implement a custom function to convert a list of mixed numeric types into a 1D array with a specified dtype.
  • Convert a list to a NumPy array and then verify the order of elements using slicing techniques.
  • Transform a list into a 1D array and compare its contents with the original list element by element.

Go to:


PREV : Print NumPy Version
NEXT : Create 3x3 Matrix (2 to 10)


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.