Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python appending a list in a for loop with numpy array data

I am writing a program that will append a list with a single element pulled from a 2 dimensional numpy array. So far, I have:

# For loop to get correlation data of selected (x,y) pixel for all bands
zdata = []
for n in d.bands:
    cor_xy = np.array(d.bands[n])
    zdata.append(cor_xy[y,x])

Every time I run my program, I get the following error:

Traceback (most recent call last):
    File "/home/sdelgadi/scr/plot_pixel_data.py", line 36, in <module>
        cor_xy = np.array(d.bands[n])
TypeError: only integer arrays with one element can be converted to an index

My method works when I try it from the python interpreter without using a loop, i.e.

>>> zdata = []
>>> a = np.array(d.bands[0])     
>>> zdata.append(a[y,x])
>>> a = np.array(d.bands[1])
>>> zdata.append(a[y,x])
>>> print(zdata)
[0.59056658, 0.58640128]

What is different about creating a for loop and doing this manually, and how can I get my loop to stop causing errors?

like image 976
Serena Delgadillo Avatar asked Dec 30 '25 09:12

Serena Delgadillo


1 Answers

You're treating n as if it's an index into d.bands when it's an element of d.bands

zdata = []
for n in d.bands:
    cor_xy = np.array(n)
    zdata.append(cor_xy[y,x])

You say a = np.array(d.bands[0]) works. The first n should be exactly the same thing as d.bands[0]. If so then np.array(n) is all you need.

like image 82
candied_orange Avatar answered Jan 01 '26 23:01

candied_orange