NumPy - Array from Existing Data
NumPy - Creating Arrays From Existing Data
Section titled “NumPy - Creating Arrays From Existing Data”NumPy provides several functions to create new arrays based on existing data structures like Python lists, tuples, or raw memory buffers.
numpy.asarray()
Section titled “numpy.asarray()”This function converts various Python sequence types (lists, tuples, lists of tuples, etc.) into a NumPy ndarray. It’s similar to numpy.array(), but asarray() avoids making a copy if the input is already an ndarray of the desired dtype.
numpy.asarray(a, dtype=None, order=None)Parameters:
| Parameter | Description |
|---|---|
| a | Input data, typically a Python list, tuple, or other sequence. |
| dtype | Optional. Desired data type for the output array. If not specified, NumPy infers it from the input data. |
| order | Optional. Memory layout: ‘C’ (row-major, default) or ‘F’ (column-major). |
Use asarray() when you want to ensure you have an ndarray but want to avoid unnecessary data copying if the input is already suitable.
Example 1: Convert list to ndarray
Section titled “Example 1: Convert list to ndarray”Basic conversion of a Python list.
import numpy as np
my_list = [1, 2, 3]a = np.asarray(my_list)
print(a)print(type(a))Output:
[1 2 3]<class 'numpy.ndarray'>Example 2: Specifying dtype
Section titled “Example 2: Specifying dtype”Converting a list and setting the data type to float.
import numpy as np
my_list = [1, 2, 3]a = np.asarray(my_list, dtype=float)
print(a)print(a.dtype)Output:
[1. 2. 3.]float64Example 3: Convert tuple to ndarray
Section titled “Example 3: Convert tuple to ndarray”Converting a Python tuple works similarly.
import numpy as np
my_tuple = (1, 2, 3)a = np.asarray(my_tuple)
print(a)Output:
[1 2 3]Example 4: Convert list of tuples
Section titled “Example 4: Convert list of tuples”If inner sequences have different lengths, the resulting array will have dtype=object.
import numpy as np
list_of_tuples = [(1, 2, 3), (4, 5)] # Note: inner tuples have different lengthsa = np.asarray(list_of_tuples)
print(a)print(a.dtype)Output:
[(1, 2, 3) (4, 5)]objectnumpy.frombuffer()
Section titled “numpy.frombuffer()”This function creates a 1D ndarray by interpreting data from a buffer object (like bytes) directly, without copying data. Useful for handling binary data or interfacing with low-level libraries.
numpy.frombuffer(buffer, dtype=float, count=-1, offset=0)Parameters:
| Parameter | Description |
|---|---|
| buffer | An object exporting the buffer interface (e.g., bytes, bytearray). |
| dtype | Data type of the elements to interpret from the buffer. |
| count | Number of items to read. -1 (default) means read as many as possible. |
| offset | Start reading the buffer from this offset (in bytes). |
Example: Creating array from bytes
Section titled “Example: Creating array from bytes”Interpreting a byte string as an array of single-byte characters.
import numpy as np
# Create a byte string (note the 'b' prefix)s = b'Hello World'
# Interpret the buffer as an array of 1-byte strings ('S1')a = np.frombuffer(s, dtype='S1')
print(a)Output:
[b'H' b'e' b'l' b'l' b'o' b' ' b'W' b'o' b'r' b'l' b'd']Note: Modifying the array created by frombuffer will modify the original buffer if it’s mutable (like a bytearray).
numpy.fromiter()
Section titled “numpy.fromiter()”Creates a 1D ndarray by consuming items from any Python iterable (like generators, lists, range objects). This can be memory-efficient for large sequences, as it doesn’t require the entire sequence to exist in memory at once (if the iterable yields items one by one).
numpy.fromiter(iterable, dtype, count=-1)Parameters:
| Parameter | Description |
|---|---|
| iterable | Any Python object that can be iterated over. |
| dtype | Data type of the resulting array. This must be specified. |
| count | Number of items to read from the iterator. -1 (default) means consume all items. |
First, let’s see a standard Python list created using range().
Example 1: Using Python range
Section titled “Example 1: Using Python range”# Create a standard Python list using range in Python 3# (range itself is an iterable, list() consumes it)my_list = list(range(5))print(my_list)Output:
[0, 1, 2, 3, 4]Example 2: Using fromiter with range
Section titled “Example 2: Using fromiter with range”Creating an ndarray directly from the range iterable.
import numpy as np
# Create an iterable (range object)iterable = range(5)
# Use the iterator to create an ndarray with float dtypex = np.fromiter(iterable, dtype=float)
print(x)print(x.dtype)Output:
[0. 1. 2. 3. 4.]float64