Numpy 相当于双循环
Numpy equilvalent of double-loop
我想在 numpy 中做同样的事情:
upper_triangle = []
for i in range(len(points)-1):
for j in range(i+1,len(points)):
upper_triangle.append(points[i],points[j])
开始于:
r1 = np.genfromtxt(path_to_csv, dtype=float, delimiter=',', names=True, max_rows=10).reshape(10,1)
print(r1)
[[(46.5850122581, 5.58578294146)]
[(48.1923697643, 6.72962889202)]
[(50.3091545259, 3.02186108116)]
[(49.1339723471, -0.158515066328)]
[(42.9817651679, 2.01049024009)]
[(44.3029325431, 5.00596735706)]
[(43.8825601072, 2.98664718926)]
[(48.0980144211, 5.14070044621)]
[(48.8361825401, 2.56443736814)]
[(43.1412292044, 2.33961454504)]]
但是,我好像找不到相关的命令。
假设您已经有一个 (n, 2)
坐标数组,您可以使用 np.triu_indices
:
i, j = np.triu_indices(points.shape[0], k=1) # k=1 excludes the main diagonal
upper_triangle = np.hstack((points[i], points[j]))
这将为您提供一个 (n*(n-1)/2, 4)
数组,其中每一行包含 x,y 行的 i,j 坐标在 points
中:(xi, yi, xj, yj)
.
但是,您的部分问题似乎与解析文本文件有关 - 您需要 (n, 2)
浮点数组而不是 (n, 1)
元组向量。也许您需要删除 "("
和 ")"
个字符?
我想在 numpy 中做同样的事情:
upper_triangle = []
for i in range(len(points)-1):
for j in range(i+1,len(points)):
upper_triangle.append(points[i],points[j])
开始于:
r1 = np.genfromtxt(path_to_csv, dtype=float, delimiter=',', names=True, max_rows=10).reshape(10,1)
print(r1)
[[(46.5850122581, 5.58578294146)]
[(48.1923697643, 6.72962889202)]
[(50.3091545259, 3.02186108116)]
[(49.1339723471, -0.158515066328)]
[(42.9817651679, 2.01049024009)]
[(44.3029325431, 5.00596735706)]
[(43.8825601072, 2.98664718926)]
[(48.0980144211, 5.14070044621)]
[(48.8361825401, 2.56443736814)]
[(43.1412292044, 2.33961454504)]]
但是,我好像找不到相关的命令。
假设您已经有一个 (n, 2)
坐标数组,您可以使用 np.triu_indices
:
i, j = np.triu_indices(points.shape[0], k=1) # k=1 excludes the main diagonal
upper_triangle = np.hstack((points[i], points[j]))
这将为您提供一个 (n*(n-1)/2, 4)
数组,其中每一行包含 x,y 行的 i,j 坐标在 points
中:(xi, yi, xj, yj)
.
但是,您的部分问题似乎与解析文本文件有关 - 您需要 (n, 2)
浮点数组而不是 (n, 1)
元组向量。也许您需要删除 "("
和 ")"
个字符?