mauve
mauve

Reputation: 2763

numpy array - replace certain values

I have yet to get my head around numpy array referencing.

I have arrays where the first 2 columns will always have some negative values that are necessary and the remaining columns need to have their negative values substituted with 0s. I understand that there are various ways to do this. The part that's baffling me is how to combine one of these methods with only doing it for the columns past 2.

Example array:

[[x, y, flow, element1, element2, element3] [x, y, flow, element1, element2, element3] [x, y, flow, element1, element2, element3]]

Desired result would be that for the whole array, any of the values that are negative are replaced with 0 unless they are x or y.

Upvotes: 3

Views: 2762

Answers (2)

Luke Willis
Luke Willis

Reputation: 8580

You would need to clip subsets of the arrays.

something like this:

a[2:].clip(0, None)

You could do this a couple of ways. One would be in a for loop:

for list in list_of_lists:
    list[2:] = list[2:].clip(0, None)

Or, using [:, 2:] which references your list of lists (:), and then all sublists of that (2:).

The result is basically what Joe Kingston has suggested:

list[:, 2:] = list[:, 2:].clip(0, None)

Upvotes: 3

Joe Kington
Joe Kington

Reputation: 284602

It sounds like you want:

subset = array[:, 2:]
subset[subset < 0] = 0

or as a rather unreadable one-liner:

array[:, 2:][array[:, 2:] < 0] = 0

As a more complete example:

import numpy as np

array = np.random.normal(0, 1, (10, 5))
print array

# Note that "subset" is a view, so modifying it modifies "array"
subset = array[:, 2:]
subset[subset < 0] = 0

print array

Upvotes: 4

Related Questions