如何在 for 循环中追加 np.arrays()?

How to append np.arrays() in a for-loop?

本应用是在分析天体物理数据,但问题纯粹是programming/syntax的问题。我想查看我的 53 个数据箱(每个 1D 星系光谱在不同星系半径处)并执行一些算法来确定运动学参数,例如每个 bin/radius 的旋转速度和速度色散。有人能告诉我我在 for 循环中做错了什么吗,我想在我的半径数组中获得 53 个值,但只有 2 个(大概是第一个和最后一个)。我想我会从第一个值 radius_center 开始,然后使用 np.append() 将在每次循环迭代时将半径的下一个值附加到数组,所以我最终会在数组中得到 53 个值结束。

for bin in (1, 53):
gal_data = np.loadtxt('C:/Users/bins/'+str(bin)+'_upper.txt')
loglam_gal = gal_data[0, :]
flux_gal = gal_data[1, :]
gh_moments = fcq_application(loglam_temp, flux_temp, loglam_gal, flux_gal)[0]
z = fcq_application(loglam_temp, flux_temp, loglam_gal, flux_gal)[1]

radius = gal_data[2, 2]
radius_arr = np.append(radius_center, radius)

编辑:在@Jérôme Richard 之后,我用列表做了所有事情,我在 for 循环之前用起始值初始化了列表。现在的问题是,在 运行 循环之后,我的列表中有 3 个值,而不是 53 个值,我不确定为什么。这是代码:

for bin in (1, 53):
    gal_data = np.loadtxt('C:/Users/reich/OneDrive/Dokumente/Uni/Bachelorarbeit/Python/bins/'+str(bin)+'_upper.txt')
    loglam_gal = gal_data[0, :]
    flux_gal = gal_data[1, :]
    gh_moments, z, *_ = fcq_application(loglam_temp, flux_temp, loglam_gal, flux_gal)

    radius = gal_data[2, 2]
    radius_list.append(radius)
    vel_rot = np.abs(vel_rot_center-gh_moments[0])
    vel_rot_list.append(vel_rot)
    vel_disp = gh_moments[1]
    vel_disp_list.append(vel_disp)
    h3 = gh_moments[2]
    h3_list.append(h3)
    h4 = gh_moments[3]
    h4_list.append(h4)
    z_list.append(z)
    signal_to_noise = gal_data[3, 3]
    signal_to_noise_list.append(signal_to_noise)

for bin in (1,53): 会将 (1,53) 视为仅包含 1 和 53 的元素元组,以实际遍历您需要的范围 for bin in range(1,54)(54 而不是 53,因为它是最后一个元素的non-inclusive)。

radius_arr = np.empty(53) # pre-allocate a numpy array of length 53
# btw if you wanted radius_center to be the first value, you'd want to do
# radius_arr = np.empty(54)
# radius_arr[0] = radius_center
# then in the for loop use radius_arr[i] = radius instead of radius_arr[i-1]

for i in range(1,54):
     gal_data = np.loadtxt('C:/Users/bins/'+str(bin)+'_upper.txt')
     loglam_gal = gal_data[0, :]
     flux_gal = gal_data[1, :]
     gh_moments = fcq_application(loglam_temp, flux_temp, loglam_gal, flux_gal)[0]
     z = fcq_application(loglam_temp, flux_temp, loglam_gal, flux_gal)[1]
     radius = gal_data[2, 2]

     radius_arr[i-1] = radius

对于一般知识,如果你确实想使用追加,你可以使用类似这样的东西:

radius_arr = np.array([radius_center]) # this is very inefficient
radius_list = [radius_center] # this is better
for i in range(1,54):
     ...
     radius_arr = radius_arr.append(radius) # this is very inefficient
     radius_list.append(radius) # doing it with a list first and appending the values is better

radius_list = np.array(radius_list) # can convert a list to a numpy array

python tuple