1

I have a default numpy array (speed, pressure or temperature data) like this:

a=[[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.]
   [ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.]
   [ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.]
   [30. 31. 32. 33. 34. 35. 36. 37. 38. 39.]
   [40. 41. 42. 43. 44. 45. 46. 47. nan 49.]]

I need to apply the following conditions and then use the corresponding formula

a<5 (a*5)+4
a>5 (a**2.)-2

I tried using:

a[a<5]=(a[a<5]*5.)+4.

but it does not work and I have also used the method creating Boolean matrices and then multiplying them by the formulas corresponding to the condition, like this:

les=(a<5.).astype(float)
mayor=(a>5.).astype(float)

les=les*((a*5)+4)
mayor=mayor*((a**2.)-2)

b=les+mayor

This works but it uses many lines of code and I think it is impractical and I would like to know if there is an easier way to do this.

3
  • 2
    The number of lines of code is not a measure of practicality. You could write as 1 line but it wouldn't be as readable. np.where should also work. Commented Jan 1, 2020 at 23:42
  • 2
    np.where(a<5, (a*5)+4, (a**2)-2) Commented Jan 2, 2020 at 3:52
  • What about a = 5 ? Should the value 5 be kept? Commented Jan 2, 2020 at 8:28

2 Answers 2

3

Try using a nested list comprehension

answer = [[(x*5)+4 if x<5 else (x**2.)-2 for x in row] for row in a]

This will essentially go row by row creating a new list for each row using the conditions you have defined to convert each element

Sign up to request clarification or add additional context in comments.

1 Comment

I don't think this will scale as well. It's all scalar math.
0

As suggested by hpaulj in comments, you could use np.where:

>>> np.where(a<5, (a*5)+4, (a**2)-2)

array([[4., 9., 14., 19., 24., 23., 34., 47., 62., 79.],
       [4., 9., 14., 19., 24., 23., 34., 47., 62., 79.],
       [4., 9., 14., 19., 24., 23., 34., 47., 62., 79.],
       [898., 959., 1022., 1087., 1154., 1223., 1294., 1367., 1442., 1519.],
       [1598., 1679., 1762., 1847., 1934., 2023., 2114., 2207., nan, 2399.]])

However, according to the conditions that you provided:

a<5: (a*5)+4
a>5: (a**2.)-2

for a = 5 the value of 5 should be kept unchanged. Here's one way to do it:

b = a.copy()
b[a<5] = a[a<5]*5 + 4
b[a>5] = a[a>5]**2 - 2

Result:

array([[4., 9., 14., 19., 24., 5., 34., 47., 62., 79.],
       [4., 9., 14., 19., 24., 5., 34., 47., 62., 79.],
       [4., 9., 14., 19., 24., 5., 34., 47., 62., 79.],
       [898., 959., 1022., 1087., 1154., 1223., 1294., 1367., 1442., 1519.],
       [1598., 1679., 1762., 1847., 1934., 2023., 2114., 2207., nan, 2399.]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.