Home > Enterprise >  Append output in for loop in python
Append output in for loop in python

Time:10-19

I am getting errors while using append as follows, how do I rectify this? Thank you

AttributeError Traceback (most recent call last) in 17 dest_depth = np.arange(0,max_depth,0.05) 18 vel_dd = interp1d(depth_z,vel_line,kind='linear',bounds_error=False,fill_value=n.nan,axis=0)(dest_depth) ---> 19 ypred_2D_dd.append(vel_dd) 20 z_stack_length.append(len(dest_depth)) 21 ypred_2D_dd = np.array(ypred_2D_dd)

AttributeError: 'numpy.ndarray' object has no attribute 'append'

from scipy.interpolate import interp1d

# ypred_2D (1280,251)


#convert to depth domain
n = ypred_2D.shape[1] #number of shots
dt=8e-11
ypred_2D_dd = []
z_stack_length = []
for i in range(n):
    vel_line = ypred_2D[:,i]
    depth_z = np.cumsum(vel_line * dt, axis=0) / 2
    depth_z = np.insert(depth_z[:1280-1],0,0,axis=0)
    max_depth = np.max(depth_z)
    dest_depth = np.arange(0,max_depth,0.05)
    vel_dd = interp1d(depth_z, vel_line,kind='linear',bounds_error=False,fill_value=np.nan,axis=0)(dest_depth)
    ypred_2D_dd.append(vel_dd)
    z_stack_length.append(len(dest_depth))
    ypred_2D_dd = np.array(ypred_2D_dd)
    z_stack_length = np.array(z_stack_length)
    min_z = np.min(z_stack_length)
    vel_dd_img_corr = []
for i in range(n):
    vel_line = ypred_2D_dd[i][:min_z]
    vel_dd_img_corr.append(vel_line)
    vel_dd_img_corr = np.array(vel_dd_img_corr).T
    vel_dd_img_corr[:10,:] = 299792500
    ep_ypred = 299792500**2 / vel_dd_img_corr **2

#save
#sio.savemat('Synthetic/Data/2D/ep_ypred2D.mat',{'ep':ypred_2D_dd})

CodePudding user response:

Looks like the code section below may be causing the issue:

z_stack_length.append(len(dest_depth))
ypred_2D_dd = np.array(ypred_2D_dd)
z_stack_length = np.array(z_stack_length)

As I understand, you want to append an item to the z_stack_length variable - But in the following lines, you define z_stack_length as a numpy array, which behaves differently than a regular list

Append will only work for ordinary lists, not numpy arrays - You can use either numpy.concatenate(list1 , list2) or numpy.append()

The thread below may offer some more insight:

Concatenate a NumPy array to another NumPy array

  • Related