Chr*_*sta 33 python numpy arcpy
我有一个字典,我需要转换为NumPy结构化数组.我正在使用arcpy函数NumPyArraytoTable,因此NumPy结构化数组是唯一可用的数据格式.
基于这个线程:从字典和这个线程写入numpy数组:如何将Python字典对象转换为numpy数组
我试过这个:
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)
Run Code Online (Sandbox Code Playgroud)
但我一直在努力 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)
Run Code Online (Sandbox Code Playgroud)
unu*_*tbu 52
你可以使用np.array(list(result.items()), dtype=dtype):
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 = ['id','data']
formats = ['f8','f8']
dtype = dict(names = names, formats=formats)
array = np.array(list(result.items()), dtype=dtype)
print(repr(array))
Run Code Online (Sandbox Code Playgroud)
产量
array([(0.0, 1.1181753789488595), (1.0, 0.5566080288678394),
(2.0, 0.4718269778030734), (3.0, 0.48716683119447185), (4.0, 1.0),
(5.0, 0.1395076201641266), (6.0, 0.20941558441558442)],
dtype=[('id', '<f8'), ('data', '<f8')])
Run Code Online (Sandbox Code Playgroud)
如果您不想创建元组的中间列表list(result.items()),那么您可以改为使用np.fromiter:
在Python2中:
array = np.fromiter(result.iteritems(), dtype=dtype, count=len(result))
Run Code Online (Sandbox Code Playgroud)
在Python3中:
array = np.fromiter(result.items(), dtype=dtype, count=len(result))
Run Code Online (Sandbox Code Playgroud)
为什么使用该列表[key,val]不起作用:
顺便说一句,你的尝试,
numpy.array([[key,val] for (key,val) in result.iteritems()],dtype)
Run Code Online (Sandbox Code Playgroud)
非常接近工作.如果您将列表更改为[key, val]元组(key, val),那么它将起作用.当然,
numpy.array([(key,val) for (key,val) in result.iteritems()], dtype)
Run Code Online (Sandbox Code Playgroud)
是一样的
numpy.array(result.items(), dtype)
Run Code Online (Sandbox Code Playgroud)
在Python2中,或
numpy.array(list(result.items()), dtype)
Run Code Online (Sandbox Code Playgroud)
在Python3中.
np.array处理列表与元组不同:Robert Kern解释说:
通常,元组被视为"标量"记录,并且列表会被递归.这个规则有助于numpy.array()找出哪些序列是记录,哪些是要递归的其他序列; 即哪些序列创建另一个维度,哪些是原子元素.
既然(0.0, 1.1181753789488595)被认为是那些原子元素之一,它应该是一个元组,而不是一个列表.
小智 5
如果您接受使用 pandas 则更简单:
import pandas
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}
df = pandas.DataFrame(result, index=[0])
print df
Run Code Online (Sandbox Code Playgroud)
给出:
0 1 2 3 4 5 6
0 1.118175 0.556608 0.471827 0.487167 1 0.139508 0.209416
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
116047 次 |
| 最近记录: |