我有一個字典,我需要轉換爲NumPy結構化數組。我使用的是arcpy函數NumPyArraytoTable
,所以NumPy結構化數組是唯一可以工作的數據格式。python字典numpy結構化數組
在此基礎上螺紋:Writing to numpy array from dictionary和這個線程:How to convert Python dictionary object to numpy array
我已經試過這樣:
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)
但我不斷收到以下作品expected a readable buffer object
的方法,但是是愚蠢的,顯然不適用於真實數據。我知道有一個更優雅的方法,我無法弄清楚。
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)
我提到這個答案你的使事情發生,它是行不通的。花了幾天的時間。你能幫忙嗎? http://stackoverflow.com/questions/32723802/scipy-and-preserving-mat-file-mat-matlab-data-file-structure – Raaj 2015-09-22 19:23:58
直接複製和粘貼代碼示例給出錯誤。我通過將'result.items()'更改爲'list(result.items())'來修復它。 Python 3.5 – Atlas7 2017-09-22 00:36:54
@ Atlas7:感謝您的提醒。答案已經更新爲Python3。 – unutbu 2017-09-22 00:56:09