2

I am not new at all to Python programming, but I am completely new to the Numpy module. I need to use this module for it's very fast and efficient.

Say I have an array called noise which is defined as follows:

noise = [[uniform(0, 1) for i in range(size)] for j in range(size)]

In numpy terms, it is defined, I believe, as so:

noise = np.uniform(0, 1, (size, size))

Now say I want to generate a new array which takes the noise array and replaces every element noise[i][j] of its elements by the function function(i, j) Using python's built-in list comprehension, I would simply say:

modified_noise = [[function(i, j) for i in range(size)] for j in range(size)]

My question, is: how can I do that using the numpy module.

6
  • What's wrong with using the list comprehension? Looks like function only works with scalar inputs, right? There's no way of getting around evaluating it once for each of the size*size (i,j) pairs, is there? Commented Mar 4, 2018 at 3:10
  • I don't see how modified_noise is related to noise. function only takes coordinates as arguments, not noise. Commented Mar 4, 2018 at 3:56
  • By the way, there's no np.uniform.. noise = np.random.random_sample((size, size)) is the right expression. You also seem to be confused about the concept of 'replacing every element'. Commented Mar 4, 2018 at 5:46
  • Oh yes, there is a numpy.uniform. I used it and it actually works just as expected. Commented Mar 4, 2018 at 12:19
  • Also, modified_noise is to be constructed from noise. The two are related but only inside the definition of the function function which in my case is a turbulance function (I called it function to give you a more abstract version of the code) Commented Mar 4, 2018 at 12:28

2 Answers 2

2

You can use np.fromfunction for this:

modified_noise = np.fromfunction(lambda i, j: function(i, j), (size, size), dtype=float)

This constructs an array by executing a function over each coordinate.

Related: How can I use a range inside numpy.fromfunction?

Sign up to request clarification or add additional context in comments.

1 Comment

0

You can build a numpy array directly from a list of lists like:

Code:

np.array(modified_noise)

Test Code:

data = [[i * j for j in range(5)] for i in range(5)]
print(data)

import numpy as np
print(np.array(data))

Results:

[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8], [0, 3, 6, 9, 12], [0, 4, 8, 12, 16]]

[[ 0  0  0  0  0]
 [ 0  1  2  3  4]
 [ 0  2  4  6  8]
 [ 0  3  6  9 12]
 [ 0  4  8 12 16]]

Comments

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.