1

I'm trying to write a function that is applied to only specific columns in a numpy array and replace the input values with the new computed ones.

So for example my array looks like

array = np.arange(1,28).reshape(3,3,3)

which is:

[[[ 1  2  3]
  [ 4  5  6]
  [ 7  8  9]]

 [[10 11 12]
  [13 14 15]
  [16 17 18]]

 [[19 20 21]
  [22 23 24]
  [25 26 27]]]

now I want to apply my function to just the values in the first column of the inner arrays (1, 4, 7, 10, 13, 16, 19, 22, 25)

If I define my function as

def myfunc(x):
    return x * x

and I want to get the following output (not a separate array containing just the sliced values)

[[[  1  2  3]
  [ 16  5  6]
  [ 49  8  9]]

 [[100 11 12]
  [169 14 15]
  [256 17 18]]

 [[361 20 21]
  [484 23 24]
  [625 26 27]]]

I read a couple of tutorials, etc. that suggest slicing the array like array[:,:,0] for getting the first column, but this approach does calculation on a new array and doesn't manipulate the elements in the original array. I could vstack the newly generated array with computed values with the original one, I guess. But is there a better solution?

Thank you very much in advance!

shogoki
  • 11
  • 2
  • 1
    `array[...,0] **= 2`? – Divakar Nov 14 '16 at 08:35
  • For completeness to @Divakar's comment, be careful when using numpy's *inplace operators*, they are not as *inplace* as one would think so: http://stackoverflow.com/questions/16034672/how-do-numpys-in-place-operations-e-g-work (i.e. some times still requires a temporary copy, which might be a problem for large arrays). – Imanol Luengo Nov 14 '16 at 08:43
  • But a relative novice shouldn't be worrying about memory use or speed like that. First concern is getting the right values in a language-natural way. – hpaulj Nov 14 '16 at 11:45

0 Answers0