Home > Net >  3d numpy array perform operation along column i only
3d numpy array perform operation along column i only

Time:06-02

I have a 3d numpy array like this (as an example)

a = np.array([
        [[1, -2, 3, 4],[5, 6, 7, 8]],
        [[9, 10, 11, 12],[13, 14, 15, 16]]
])

I want to apply the following operations only to elements within the column with index 1 in the inner dimension. The elements are [-2,6,10,14] for the example above. The operations would be:

# variables used in the operations
v1, v2, v3 = 12, 4, 2

# the following two operations should only be applied to specified column across all the array

# 1st operation
a[a >= v1] = v1

# output
a = np.array([
        [[1, -2, 3, 4],[5, 6, 7, 8]],
        [[9, 10, 11, 12],[13, 12, 15, 16]]
])

# 2nd operation
f = lambda x: -2 if(x==-2) else (x-v3)/(v2-v3)
a = f(a)

# output

a = np.array([
        [[1, -2, 3, 4],[5, 2, 7, 8]],
        [[9, 4, 11, 12],[13, 5, 15, 16]]
])

Can someone help me? I have looked into several NumPy methods but can't seem to adapt to my example.

CodePudding user response:

You need to change you function to be vectorial (i.e accept an array and input and return an array as output), and slice to only apply it on the desired "column":

f = lambda x: np.where(x==-2, -2, (x-v3)/(v2-v3))

a[...,[1]] = f(a[...,[1]])

output:

array([[[ 1, -2,  3,  4],
        [ 5,  2,  7,  8]],

       [[ 9,  4, 11, 12],
        [13,  5, 15, 16]]])

CodePudding user response:

a = np.array([
        [[1, -2, 3, 4],[5, 6, 7, 8]],
        [[9, 10, 11, 12],[13, 14, 15, 16]]
])

print(a.trasnpose()[1]).reshape(1,4)

will print:

[[-2 10  6 14]]

or

a.transpose()[1].flatten()

will print:

[-2 10  6 14]

than you can do your operation on it

  • Related