How do I multiply specific numbers in n arrays?

Viewed 49

I want to multiply the first three numbers in an array with (-1) in a list of n arrays. The numpy arrays are stored through out a for loop in a list, see list below.

internal_force_list.append(internal_forces)

the list internal_force_list output looks like this

[
    array([
        [-6], [-2.5], [7.5], [6.0], [2.5], [0.18]
    ]), 
    array([
        [8.27], [0.08], [-0.18], [-8.2], [-0.08], [0.0]
    ])
]

and should look like this in the end:

[
    array([
        [6], [2.5], [-7.5], [6.0], [2.5], [0.18]
    ]), 
    array([
        [-8.27], [-0.08], [0.18], [-8.2], [-0.08], [0.0]
    ])
]

How do I solve this?

1 Answers

You can make your life easier by using numpy at all levels.

So if you have a list of arrays, convert it to an array of arrays (i.e., n-dimensional array). Then you can use slicing to modify the first three elements along the second axis.

from numpy import array
from numpy.testing import assert_array_equal

x_list = [
    array([[-6], [-2.5], [7.5], [6.0], [2.5], [0.18]]), 
    array([[8.27], [0.08], [-0.18], [-8.2], [-0.08], [0.0]])
]

expect = array([
    array([[6], [2.5], [-7.5], [6.0], [2.5], [0.18]]), 
    array([[-8.27], [-0.08], [0.18], [-8.2], [-0.08], [0.0]])
])

x_arr = array(x_list)  # shape = (2, 6, 1)

# flip the sign of the first three elements along the second axis
x_arr[:, :3, :] *= -1
print(x_arr)

That'll get you:

array([[[ 6.  ],
        [ 2.5 ],
        [-7.5 ],
        [ 6.  ],
        [ 2.5 ],
        [ 0.18]],

       [[-8.27],
        [-0.08],
        [ 0.18],
        [-8.2 ],
        [-0.08],
        [ 0.  ]]])

And we can check that it's right:

expected = array([
    array([[6], [2.5], [-7.5], [6.0], [2.5], [0.18]]), 
    array([[-8.27], [-0.08], [0.18], [-8.2], [-0.08], [0.0]])
])
assert_array_equal(x_arr, expected)
Related