[英]structured numpy ndarray, how to get values
I have a structured numpy ndarray la = {'val1':0,'val2':1} and I would like to return the vals using the 0 and 1 as keys, so I wish to return val1 when I have 0 and val2 when I have 1 which should have been straightforward however my attempts have failed, as I am not familiar with this structure. 我有一个结构化的numpy ndarray la = {'val1':0,'val2':1},我想使用0和1作为键返回val,所以当我有0和val2时我希望返回val1我有1个应该简单明了,但是我的尝试失败了,因为我对这种结构不熟悉。
How do I return only the corresponding val, or an array of all vals so that I can read in order? 如何仅返回相应的val或所有val的数组,以便可以顺序读取?
When you save a Python object (non-array), numpy
wraps it in an array. 保存Python对象(非数组)时, numpy
将其包装在数组中。 The object is pickled
: pickled
对象:
In [112]: np.save('test.npy', {'foo':34})
In newer numpy
versions, you have to explicitly allow it to load pickled items: 在较新的numpy
版本中,必须显式允许它加载腌制的物品:
In [113]: data = np.load('test.npy')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-113-c5835e6fb31e> in <module>
----> 1 data = np.load('test.npy')
/usr/local/lib/python3.6/dist-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding)
451 else:
452 return format.read_array(fid, allow_pickle=allow_pickle,
--> 453 pickle_kwargs=pickle_kwargs)
454 else:
455 # Try a pickle
/usr/local/lib/python3.6/dist-packages/numpy/lib/format.py in read_array(fp, allow_pickle, pickle_kwargs)
720 # The array contained Python objects. We need to unpickle the data.
721 if not allow_pickle:
--> 722 raise ValueError("Object arrays cannot be loaded when "
723 "allow_pickle=False")
724 if pickle_kwargs is None:
ValueError: Object arrays cannot be loaded when allow_pickle=False
In [115]: data = np.load('test.npy',allow_pickle=True)
In [116]: data
The result is an object dtype array with 1 element (0d) 结果是具有1个元素(0d)的对象dtype数组
Out[116]: array({'foo': 34}, dtype=object)
tolist
can extract that object, as will item()
. tolist
可以提取该对象, item()
也会如此。
In [117]: data.tolist()
Out[117]: {'foo': 34}
In [118]: data.tolist()['foo']
Out[118]: 34
In [119]: data.item()
Out[119]: {'foo': 34}
In [120]: data[()]
Out[120]: {'foo': 34}
That looks like a dictionary, rather than an ndarray. 看起来像字典,而不是ndarray。 Assuming you don't have multiple keys associated with the same value, you reverse the dictionary with 假设您没有与同一个值关联的多个键,则使用
la_reversed = {v: k for k, v in la.items()}
so la_reversed[0]
would be 'val1'
and la_reversed[1]
would be 'val2'
. 因此la_reversed[0]
将为'val1'
而la_reversed[1]
将为'val2'
。
You can get a list of values in the dictionary with list(la.values())
. 您可以使用list(la.values())
获得字典中的值list(la.values())
。
Just found out that I can use la.tolist() and it returns a dictionary, somehow? 刚刚发现我可以使用la.tolist()并以某种方式返回字典? when I wanted a list, alas from there on I was able to solve my problem. 当我想要一份清单时,很高兴能够解决我的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.