Summing part of 2D array in python
<p>I have a 2D array. After manipulating the x column of the array, I created a new 2D array (data2) with the new changes to the x column (and the y column remained the same). I now want to append the array of y values in data2 to a new array only if its x value is greater than 3 or less than 5. For example, if the 2D array was ([2,3], [4,5], [3.5,6], [9,7]), I would only want the y values of 5 and 6 in my new array because their x values are between 3 and 5. I'm stuck. please help!</p>

<pre><code>import numpy as np
import matplotlib.pyplot as plt

data = np.loadtxt('blah.txt') #blah.txt is a 2d array

c = (3*10)^8

x = c /((data[:,0])*10)

y = data[:,1]


data2 = np.array((x,y)).T

def new_yarray(data2):

    yarray =[]

    if data2[:,0] &lt;= 5 or data2[:,0] &gt;= 3:

        np.append(data2[:,1])

    print yarray

    return yarray
</code></pre>

<p>Here is a one-liner solution broken in several steps for clarity.</p>

<p>Given an array</p>

<pre><code>&gt;&gt;&gt; a
array([[ 2. ,  3. ],
       [ 4. ,  5. ],
       [ 3.5,  6. ],
       [ 9. ,  7. ]])
</code></pre>

<p>You can find the <em>index</em> of the elements where the <code>x</code> value is more than 3 and less than 5 by using <code>np.where()</code>:</p>

<pre><code>&gt;&gt;&gt; np.where(np.logical_and(a[:,0] &gt; 3,a[:,0] &lt; 5))
(array([1, 2]),)
</code></pre>

<p>Where <code>a[:,0] = array([ 2. ,  4. ,  3.5,  9. ])</code> is the array of all the <code>x</code> values. Now, you can get all the corresponding <code>y</code> values where <code>3 &lt; x &lt; 5</code> by:</p>

<pre><code>&gt;&gt;&gt; a[np.where(np.logical_and(a[:,0] &gt; 3,a[:,0] &lt; 5))][:,1]
array([ 5.,  6.])
</code></pre>

python arrays function numpy append