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>You can use this function to flatten the list and then append the values according. </p>

<pre><code>def flatten_list(a, result=None):
    """ Flattens a nested list. """
    if result is None:
        result = []

    for x in a:
        if isinstance(x, list):
            flatten_list(x, result)
        else:
            result.append(x)
    return result

lst = ([2,3], [4,5], [3.5,6], [9,7])

lst = flatten_list(lst)

new_lst = []
for i in lst:
    if (float(i) &gt; 3 and float(i) &lt; 5):
        new_lst.append(i)
print new_lst
</code></pre>

<p>In this case, only 3.5 and 4 is greater than 3 and less 5...</p>

python arrays function numpy append