0

I am using a data object that is a list of numpy arrays of different shapes. I would like to treat the data object as a single numpy object, such that I can add, subtract and scale these objects as if they were pure numpy arrays:

# Defining the data objects:
d1 = [numpy.random.rand(n**2).reshape(n, n) for n in range(1, 5)]
d2 = [numpy.random.rand(n**2).reshape(n, n) for n in range(1, 5)]

# The operation I want to perform:
d3 = [a1 + 2*a2 for a1, a2 in zip(d1, d2)]

# What I really would like to write:
d3 = d1 + 2*d2   # (not valid for lists of arrays)

What is the easiest way to define the objects d1 and d2 such that I can use the last line?

The reason I ask is because I want to reuse some code that assumes that d1 and d2 are simple numpy arrays that can be added and scaled.

2
  • @Moses Koledoye: The shapes of the arrays match. See the example. Commented Jan 2, 2017 at 14:28
  • Pay attention to shape and dtype when creating an array from these lists. Since the subarrays differ in shape, the combination will be a 1d array of array objects, not a multidimensional array of floats. Some, but not all, numpy math propagates through those objects. Commented Jan 2, 2017 at 17:32

1 Answer 1

1

Simply defining them as numpy.array works:

d1 = numpy.array([numpy.random.rand(n**2).reshape(n, n) for n in range(1, 5)])
d2 = numpy.array([numpy.random.rand(n**2).reshape(n, n) for n in range(1, 5)])
d3 = d1 + 2 * d2

Or if you want to keep d1 and d2 as regular lists you can use numpy.asarray:

d1_ = numpy.asarray(d1)
d2_ = numpy.asarray(d2)
d3 = d1_ + 2 * d2_
Sign up to request clarification or add additional context in comments.

2 Comments

What does asarray do that's different?
@hpaulj nothing. I just meant it as an option if one already has the lists stored somewhere and does not want to change the defining lines

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.