Creating numpy arrays from existing data


Martin McBride, 2019-09-15
Tags arrays data types
Categories numpy

This article is part of a series on numpy. If you find this article useful you might like our Numpy Recipes e-book.

In this section we will look at how to create numpy arrays from existing data.

From an existing sequence

An easy way to create an array based on data is to use thearray function:

import numpy as np

k1 = [1, 3, 5, 7]
d1 = np.array(k1)
print(d1)

This creates a numpy array d1 based on the list k1:

[1 3 5 7]

You can do this for more dimensions:

k2 = [[10, 20, 30], [40, 50, 60]]
d2 = np.array(k2)
print(d2)

giving:

[[10 20 30]
 [40 50 60]]

array will accept any sequence, or numpy array, or anything that behaves like a numpy array.

Visit the PythonInformer Discussion Forum for numeric Python.


Tag cloud

2d arrays abstract data type alignment and array arrays bezier curve built-in function close closure colour comparison operator comprehension context conversion data types device space dictionary duck typing efficiency encryption enumerate filter font font style for loop function function plot functools generator gif gradient html image processing imagesurface immutable object index input installing iter iterator itertools lambda function len linspace list list comprehension logical operator lru_cache mandelbrot map mutability named parameter numeric python numpy object open operator optional parameter or path positional parameter print pure function radial gradient range recursion reduce rotation scaling sequence slice slicing sound spirograph str stream string subpath symmetric encryption template text text metrics transform translation transparency tuple unpacking user space vectorisation webserver website while loop zip

Copyright (c) Axlesoft Ltd 2020