python dict to numpy structured array

前端 未结 5 506
星月不相逢
星月不相逢 2020-12-02 12:04

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

5条回答
  •  广开言路
    2020-12-02 12:49

    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.

    import numpy as np
    result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}
    
    names = 0
    values = 1
    array = np.empty(shape=(2, len(result)), dtype=float)
    array[names] = result.keys()
    array[values] = result.values()
    

    But my favorite is this (simpler):

    import numpy as np
    result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}
    
    arrays = {'names': np.array(result.keys(), dtype=float),
              'values': np.array(result.values(), dtype=float)}
    

提交回复
热议问题