0

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.

How do I return only the corresponding val, or an array of all vals so that I can read in order?

1
  • 1
    This {'val1':0,'val2':1}, is a dictionary, not a structured array. If you do have one please share a MCVE Commented Sep 15, 2019 at 21:46

3 Answers 3

2

When you save a Python object (non-array), numpy wraps it in an array. The object is pickled:

In [112]: np.save('test.npy', {'foo':34})                                              

In newer numpy versions, you have to explicitly allow it to load pickled items:

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)

Out[116]: array({'foo': 34}, dtype=object)

tolist can extract that object, as will 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}
Sign up to request clarification or add additional context in comments.

Comments

0

That looks like a dictionary, rather than an 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'.

You can get a list of values in the dictionary with list(la.values()).

7 Comments

In my debugger it says it is an ndarray and when I try to use items or values as I would with a dictionary I get: labels = list(lb.values()) AttributeError: 'numpy.ndarray' object has no attribute 'values'
Can you edit your question to include an MCVE per yatu's comment or at least the declaration of this variable in your code?
It is a variable I saved as .npy and the variable is actually the class indices value that I get while creating training dataset generators in keras: train_generator.class_indices, here (keras.io/preprocessing/image) it says: The dictionary containing the mapping from class names to class indices can be obtained via the attribute class_indices.
and I save it as: labels = (train_generator.class_indices) np.save('/home/d/Desktop/s/classes', labels)
If the documentation states that class_indices should be a dictionary, I'm not sure why that wouldn't be the case in your code. Again, if you provide more code it will be easier to determine what the problem is.
|
0

Just found out that I can use la.tolist() and it returns a dictionary, somehow? when I wanted a list, alas from there on I was able to solve my problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.