may7even
may7even

Reputation: 129

Divide positive and negative elements with different numbers. Python

I have a (8864,40) array A, containing both negative and positive values. I wanna divide the positive values of the array with the maximum value of A, and divide the negative values with the minimum of A. Is it possible to do this whilst also keeping the shape of the array A? Any help would be appreciated.

Upvotes: 0

Views: 128

Answers (3)

dudung
dudung

Reputation: 719

If it is a list you can use list comprehension such as

x = [-2, 1, 3, 0, -4, -1, 0, 5, 2]
y = [i / max(x) if i > 0 else i / abs(min(x)) for i in x]

print(x)
print(y)

that produces

[-2, 1, 3, 0, -4, -1, 0, 5, 2]
[-0.5, 0.2, 0.6, 0.0, -1.0, -0.25, 0.0, 1.0, 0.4]

where sign of the number - or + is conserved. Without the use of abs() you will get only positive values.

I do not quite understand by the phrase

Is it possible to do this whilst also keeping the shape of the array A?

By any change the shape means the sign?

Upvotes: 1

fabi
fabi

Reputation: 31

please see the snipped below

A[A > 0] /= np.max(A)
A[A < 0] /= np.min(A) 

Upvotes: 2

Julien
Julien

Reputation: 15071

This?

np.where(A > 0, A/A.max(), A/A.min())

Upvotes: 1

Related Questions