简体   繁体   English

Python 遍历每个元素并删除第n个元素

[英]Python loop through every element and delete nth element

I'm having trouble figuring out how to loop through an array of arrays and delete the nth element.我无法弄清楚如何遍历 arrays 数组并删除第 n 个元素。 Ie. IE。 the first loop would keep everything but delete the first element, the second loop would keep everything but delete the second element, etc. Basically turn my hardcoding section into a loop第一个循环将保留所有内容,但删除第一个元素,第二个循环将保留所有内容,但删除第二个元素,等等。基本上将我的硬编码部分变成一个循环

x1 = np.array([1,2,4,6])
y1 = np.array([2,4,6,3])
x2 = np.array([2,4,2,7])
y2 = np.array([2,5,3,4])
x3 = np.array([3,5,4,3])
y3 = np.array([2,6,1,2])
x4 = np.array([6,6,4,7])
y4 = np.array([8,9,8,4])

xs = np.array([x1,x2,x3,x4])
ys = np.array([y1,y2,y3,x4])

linear_r2 = []
quadratic_r2 = []

def linear_func(x, a, b):
    return (a * x) + b

def fit_r2(ydata, yfit):
    residuals = ydata - yfit 
    ss_res = np.sum(residuals**2)
    ss_tot = np.sum((ydata - np.mean(ydata))**2)
    r2 = 1 - (ss_res / ss_tot)
    return r2

#hardcoding
xs_1 = xs[:, 1:]
ys_1 = ys[:, 1:]
xdata = xs_1[0,:]
ydata = ys_1[0,:]
popt, _ = curve_fit(linear_func, xdata, ydata)
yfit = linear_func(xdata, *popt)
linear_1 = fit_r2(ydata,yfit)
linear_r2.append(linear_1)

xs_2 = np.delete(xs,1,axis = 1)
ys_2 = np.delete(ys,1,axis = 1)
xdata = xs_2[0,:]
ydata = ys_2[0,:]
popt, _ = curve_fit(linear_func, xdata, ydata)
yfit = linear_func(xdata, *popt)
linear_2 = fit_r2(ydata,yfit)
linear_r2.append(linear_2)

You could use something like this to delete a element in a double array.您可以使用类似这样的方法来删除双精度数组中的元素。

arr = [[1,0,0],
       [0,1,0],
       [0,0,1]]
for position in range(len(arr)):
    arr[position].pop(position)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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