scipy.spatial 尝试 运行 kdtree 时出现 ValueError

scipy.spatial ValueError when trying to run kdtree

背景: 我正在尝试 运行 最近的邻居,在具有 201 条记录的 shapefile 上使用 cKDtree 函数 lat/lons针对 8760 小时(一年的总小时数)的时间序列数据集。我收到一个错误,自然我查了一下。我发现了这个:scipy.spatial ValueError: "x must consist of vectors of length %d but has shape %s" 这是同样的错误,但我无法理解这个错误是如何解决的。

工作流程: 我从 shapefile 中提取了 x 和 y 坐标,并将它们存储在名为 x_vectory_vector 的单独数组中。 8760数据是一个hdf5文件。我使用 h5_coords = np.vstack([meta['latitude'], meta['longitude']]).T 提取坐标。

现在我尝试运行 kdtree,

# Run the kdtree to match nearest values
tree = cKDTree(np.vstack([x_vector, y_vector]))
kdtree_indices = tree.query(h5_coords)[1]

但它会导致同样的回溯错误。

回溯错误:

Traceback (most recent call last):
File "meera_extract.py", line 45, in <module>
kdtree_indices = tree.query(h5_coords)[1]
File "scipy/spatial/ckdtree.pyx", line 618, in scipy.spatial.ckdtree.cKDTree.query (scipy/spatial/ckdtree.cxx:6996)
ValueError: x must consist of vectors of length 201 but has shape (1, 389880)

帮帮我,Whosebug。你是我唯一的希望。

所以看来我需要阅读 vstackcolumn_stack 的区别以及 t运行spose 的用法,即 .T。如果有人遇到同样的问题,这里是我为使 cKDtree 工作所做的更改。如果其他人遇到此问题,希望它会有所帮助。非常感谢社区的评论帮助解决这个问题!

我将 hdf5 坐标的引入方式从 vstack 更改为 column_stack 并删除了 t运行spose .T.

# Get coordinates of HDF5 file
h5_coords = np.column_stack([meta['latitude'], meta['longitude']])

我没有尝试在树中添加点,而是创建了一个新变量来保存它们:

# combine x and y
vector_pnts = np.column_stack([x_vector, y_vector])

然后我运行kdtree没有任何错误。

# Run the kdtree to match nearest values
tree = cKDTree(vector_pnts)
kdtree_indices = tree.query(h5_coords)[1]