NumPy: Convert a list of numeric value into a one-dimensional NumPy array
NumPy: Array Object Exercise-2 with Solution
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:
Previous: Write a NumPy program to print the NumPy version in your system.
Next: Write a NumPy program to create a 3x3 matrix with values ranging from 2 to 10.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics