Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

numpy
array
communitycreator

How to create an array from existing data in NumPy

Eman Kashif

The asarray() method in NumPy can be used to create an array from data that already exists in the form of lists or tuples.

Syntax

numpy.asarray(a, dtype=None, order=None, *, like=None)

Parameters

  1. a: Input data. a can be in the form of a tuple, a list, a list of tuples, a tuple of tuples, or a tuple of lists.

  2. dtype: The data type to be applied to each element of the array. This parameter is optional. By default, the data type is inferred from a.

  3. order: A memory layout that can be set as F,C,K, or A.

    • K and A depend on the order of a.
    • F is a column-major representation, and C is a row-major memory representation.
    • This parameter is optional. The default value of the parameter is C.
  4. like: like allows arrays that are not NumPy arrays to be created. This parameter is optional. The default value of the parameter is None.

Return value

The function returns an array.

Code

1. Create an array from a list

import numpy as np

#create numpy arrays from lists
list1=[5, 3, 6, 2, 1, 5]
list2=[10, 3, 32, 95, 12, 34, 3]

#print type of both lists
print("Type of list1: ", type(list1))
print("Type of list2: ", type(list2))

#create arrays from the lists
array1 = np.asarray(list1)
array2 = np.asarray(list2)

#print type of both arrays
print("Type of array1: ", type(array1))
print("Type of array2: ", type(array2))

2. Create an array from a tuple

import numpy as np

#create numpy arrays from tuples
tuple1 = (43, 21, 32, 67, 21, 5)
tuple2=(8, 6, 1, 0, 2, 1, 5)

#print type of both tuples
print("Type of tuple1: ", type(tuple1))
print("Type of tuple2: ", type(tuple2))

#create arrays from the tuples
array1 = np.asarray(tuple1)
array2 = np.asarray(tuple2)

#print type of both arrays
print("Type of array1: ", type(array1))
print("Type of array2: ", type(array2))

3. Create an array from a list of tuples

import numpy as np

#create an numpy array from a list of tuples
list1 = [(3, 5),(6, 4, 8)]

#print type 
print("Type of list1: ", type(list1))

#create array from the list of tuples
array1 = np.asarray(list1)

#print type
print("Type of array1: ", type(array1))

RELATED TAGS

numpy
array
communitycreator
RELATED COURSES

View all Courses

Keep Exploring