简体   繁体   中英

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) 

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM