scipy.spatial ValueError when trying to run kdtree
<p><strong>Background:</strong> I am trying to run a nearest neighbor using the <code>cKDtree</code> function on a shapefile that has 201 records with lat/lons against a time series dataset of 8760 hours (total hours in a year). I am getting an error, naturally I looked it up. I found this: <a href="http://stackoverflow.com/questions/14264682/scipy-spatial-valueerror-x-must-consist-of-vectors-of-length-d-but-has-shape">scipy.spatial ValueError: &quot;x must consist of vectors of length %d but has shape %s&quot;</a> which is the same error, but I am having trouble understanding how exactly this error was resolved.</p>

<p><strong>Workflow:</strong> I pulled the x &amp; y coordinates out of the shapefile and stored them in separate arrays called <code>x_vector</code> and <code>y_vector</code>. The 8760 data is an hdf5 file. I pulled the coordinates out using <code>h5_coords = np.vstack([meta['latitude'], meta['longitude']]).T</code>. </p>

<p>Now I try to run the kdtree,</p>

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

<p>but it results in this same traceback error.</p>

<p><strong>Traceback Error:</strong></p>

<pre><code>Traceback (most recent call last):
File "meera_extract.py", line 45, in &lt;module&gt;
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)
</code></pre>

<p>Help me, stackoverflow. You're my only hope.</p>

<p>So it seems I need to read up on the differences of <code>vstack</code> &amp; <code>column_stack</code> and the use of transpose i.e. <code>.T</code>. If anyone has the same issue here is what I changed to make the <code>cKDtree</code> work. Hopefully it will help if someone else runs into this issue. Many thanks to comments from the community to help solve this!</p>

<p>I changed how the <code>hdf5</code> coordinates were brought in from <code>vstack</code> to <code>column_stack</code> and removing the transpose <code>.T</code>.</p>

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

<p>Instead of trying to add the points in the tree I made a new variable to hold them:</p>

<pre><code># combine x and y
vector_pnts = np.column_stack([x_vector, y_vector])
</code></pre>

<p>Then I ran the kdtree without any error.</p>

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

python numpy kdtree