Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using python numpy linspace in for loop

I am trying to use linspace in a for loop. I would like intervals of 0.5 between 0 and 10. It appears the z_bin is executing properly.

My question: How can I use linspace correctly in the for loop in place of the range function that is shown next to it in the comment line? What do I need to change in the loop as I move from working with integers to working with decimals?

z_bin = numpy.linspace (0.0,10.0,num=21) 
print 'z_bin: ', z_bin
num = len(z_bin)

grb_binned_data = []
for i in numpy.linspace(len(z_bin)-1): #range(len(z_bin)-1):
    zmin = z_bin[i]
    zmax = z_bin[i+1]
    grb_z_bin_data = []
    for grb_row in grb_data:
        grb_name = grb_row[0]
        ra = grb_row[1]
        dec = grb_row[2]
        z = float(grb_row[3])
        if z > zmin and z <= zmax:
            grb_z_bin_data.append(grb_row)
    grb_binned_data.append(grb_z_bin_data) 
like image 558
CuriousGeorge119 Avatar asked Oct 17 '25 03:10

CuriousGeorge119


2 Answers

You should not use the output of linspace to index an array! linspace generates floating point numbers and array indexing requires an integer.

From your code it looks like what you really want is something like this:

z_bin = numpy.linspace(0.0, 10.0, 21)

for i in range(len(z_bin)-1):
    zmin = z_bin[i]
    zmax = z_bin[i+1]

    # do some things with zmin/zmax

zmin and zmax will still be floating point (decimal) numbers.

like image 181
dshepherd Avatar answered Oct 18 '25 19:10

dshepherd


An easier way to do this would be to use the zip function:

z_bin = numpy.linspace(0.0, 10.0, 21)

for z_min, z_max in zip(z_bin[:-1], z_bin[1:]):
    print z_min, z_max
like image 26
pranav Avatar answered Oct 18 '25 18:10

pranav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!