Skip to content
Advertisement

how to use fromiter and ndnumerate together

I’m currently trying to manually implement a function to represent the KNN graph of a set of points as an incidence matrix, and my idea was to take the rows of an affinity matrix(n x n matrix representing the distance between the n points), enumerate and sort them, then return indices for the first K elements

JavaScript

the errors I get are dependent on the value of dtype. the obvious choice I thought was dtype=(np.intp, np.float64) or dtype=(int,np.float64) but this returns the error: ValueError: setting an array element with a sequence. meaning I’m trying to unpack multiple values to a single spot

when inspecting the output of ndenumerate in a loop, the first value appears to be a single value inside a tuple:

JavaScript
JavaScript

but setting dtype=((int,), np.float64) throws the error: TypeError: Tuple must have size 2, but has size 1

Is there a way to use fromiter and ndenumerate together, or are they somehow incompatible?

Advertisement

Answer

ndenumerate produces, for each element, a indexing tuple and the value.

JavaScript

That makes more sense when the array is 2d or more. The indexing tuples will have 2 or more values:

JavaScript

With ‘plain’ enumerate, you get a 2 element tuple:

JavaScript

With fromiter and the compound dtype:

JavaScript

edit

For a 1d array, this function produces the same structured array as your fromiter

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement