I have a dictionary that I need to convert to a NumPy structured array. I'm using the arcpy function NumPyArraytoTable
, so a NumPy structured array is the only data format that will work.
Based on this thread: Writing to numpy array from dictionary and this thread: How to convert Python dictionary object to numpy array
I've tried this:
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}
names = ['id','data']
formats = ['f8','f8']
dtype = dict(names = names, formats=formats)
array=numpy.array([[key,val] for (key,val) in result.iteritems()],dtype)
But I keep getting expected a readable buffer object
The method below works, but is stupid and obviously won't work for real data. I know there is a more graceful approach, I just can't figure it out.
totable = numpy.array([[key,val] for (key,val) in result.iteritems()])
array=numpy.array([(totable[0,0],totable[0,1]),(totable[1,0],totable[1,1])],dtype)
I would prefer storing keys and values on separate arrays. This i often more practical. Structures of arrays are perfect replacement to array of structures. As most of the time you have to process only a subset of your data (in this cases keys or values, operation only with only one of the two arrays would be more efficient than operating with half of the two arrays together.
But in case this way is not possible, I would suggest to use arrays sorted by column instead of by row. In this way you would have the same benefit as having two arrays, but packed only in one.
But my favorite is this (simpler):
Even more simple if you accept using pandas :
gives :
You could use
np.array(list(result.items()), dtype=dtype)
:yields
If you don't want to create the intermediate list of tuples,
list(result.items())
, then you could instead usenp.fromiter
:In Python2:
In Python3:
Why using the list
[key,val]
does not work:By the way, your attempt,
was very close to working. If you change the list
[key, val]
to the tuple(key, val)
, then it would have worked. Of course,is the same thing as
in Python2, or
in Python3.
np.array
treats lists differently than tuples: Robert Kern explains:Since
(0.0, 1.1181753789488595)
is considered one of those atomic elements, it should be a tuple, not a list.Let me propose an improved method when the values of the dictionnary are lists with the same lenght :