【发布时间】:2021-08-20 10:38:08
【问题描述】:
我正在尝试根据 x 和 y 点位于 python 网格的特定部分中来标记它们。这些点存储在 pandas 数据框中。
这里我有一个坐标的散点图,在它们上方我正在绘制网格。 整个网格要大得多,从左下点 (500,1250) 到右上角 (2750, 3250),这意味着整个网格是 225x200 部分。
我想遍历网格的各个部分并检查一个点是否在里面。如果一个点在该部分内,我想为该点添加一个标签。标签应与部分名称相同。 我想在数据框中添加一个名为“section”的列,用于存储点所属的部分。
在示例中(上图),我想用 770
我的代码目前如下所示:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
df = pd.read_csv('./file.csv', sep=';')
x_min = df['X[mm]'].min()
x_max = df['X[mm]'].max()
y_min = df['Y[mm]'].min()
y_max = df['Y[mm]'].max()
#side of the square in mm:
square_side = 10
xs = np.arange(x_min, x_max+square_side, square_side)
ys = np.arange(y_min, y_max+square_side, square_side)
x_2, y_2 = np.meshgrid(xs, ys, indexing = 'ij')
fig, ax = plt.subplots(figsize=(9,9))
ax.plot(df['X[mm]'], df['Y[mm]'], linewidth=0.2, c='black')
#plot meshgrid as grid instead of points:
segs1 = np.stack((x_2[:,[0,-1]],y_2[:,[0,-1]]), axis=2)
segs2 = np.stack((x_2[[0,-1],:].T,y_2[[0,-1],:].T), axis=2)
plt.gca().add_collection(LineCollection(np.concatenate((segs1, segs2))))
ax.set_aspect('equal', 'box')
plt.show()
我还有一个函数可以确定点是否在矩形内(这不使用网格):
def is_inside_rect(M, A, B, D):
'''Check if a point M is inside a rectangle with corners A, B, C, D'''
# 0 <= dot(BC,BM) <= dot(BC,BC)
#print(np.dot(B - A, D - A))
return 0 <= np.dot(B - A, M - A) <= np.dot(B - A, B - A) and 0 <= np.dot(D - B, M - B) <= np.dot(D - B, D - B)
我想过在这样的while循环中使用它:
x = x_min
y = y_min
while (x <= x_max + square_side) and (y <= y_max + square_side):
A = np.array([x, y])
B = np.array([x + square_side, y])
D = np.array([x + square_side, y + square_side])
print(A, B, D)
df['c'] = df[['X[mm]', 'Y[mm]']].apply(lambda coord: 'red' if is_inside_rect(np.array(coord), A, B, D) else 'black', axis=1)
x += square_side
y += square_side
但这非常慢,而且每次迭代都会改变所有点的颜色。
【问题讨论】:
标签: python pandas numpy matplotlib