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.
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 |
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics