Home > Mobile >  how to select values from two arrays according to a value condition from another array?
how to select values from two arrays according to a value condition from another array?

Time:09-17

I have 3 arrays:

a=np.array([-10,-6,-4,0,14,2,4,12,3,6,8,14,11])
b=np.array([0,5,5,6,8,10,2,2,0,0,0,0,7])
c=np.array([4,6,10,40,22,14,20,8,12,4,3,6,-4])

I want to make a plot of c (y-axis) values against a(x-axis) values but for only those values that correspond to b=0 and also only for a>0. So, I want to find a way to produce new arrays which will give: a_new= [3,6,8,14] and corresponding (matching with the indices) c_new= [12,4,3,6]. Then I will just plot c_new vs a_new.

This is just a sample data. My actual data set is quite large, so it will be great if we can find a method that's fast. Any help is appreciated!

CodePudding user response:

You can create an array with your conditions and use it to select from a and c.

import matplotlib.pyplot as plt

select = (b == 0) & (a > 0)

plt.plot(a[select], c[select])
plt.xlabel('a')
plt.ylabel('c');

Output

a vs c

CodePudding user response:

You can achieve it with the following:

Python 3.6.9 (default, Jan 26 2021, 15:33:00) 
>>> import numpy as np
>>> a = np.array([-10, -6, -4, 0, 14, 2, 4, 12, 3, 6, 8, 14, 11])
>>> b = np.array([0, 5, 5, 6, 8, 10, 2, 2, 0, 0, 0, 0, 7])
>>> c = np.array([4, 6, 10, 40, 22, 14, 20, 8, 12, 4, 3, 6, -4])
>>> i1 = a > 0
>>> i2 = b == 0
>>> i = i1 & i2
>>> a[i]
array([ 3,  6,  8, 14])
>>> c[i]
array([12,  4,  3,  6])
  • Related