Home > Blockchain >  unable to get length of items in .npy file
unable to get length of items in .npy file

Time:11-10

I have a .npy file here

Its just a file with an object that is a list of images and their labels. for example:

{
'2007_002760': array([0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0.], dtype=float32), 
'2008_004036': array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 0., 0.,0., 0., 0.], dtype=float32)
}

I want to open the file and get its length, and then possibly add to it or modify it

I am able to open the file, but I cant get the length of items in it. Heres how i open it:

import numpy as np
file = np.load('cls_labels.npy', allow_pickle = True)
print(file.size)

What am I missing here?

CodePudding user response:

Your file contains a dictionary wrapped inside a 0-dimensional numpy object. The magic to extract the actual information is:

my_dictionary = file[()]

This is a standard dictionary whose keys are strings like '2008_004036' and whose values are numpy arrays.


Edit: And as mentioned above, you shouldn't be saving dictionaries using numpy.save(), you should have been using pickle. You end up with horrors like file[()].

CodePudding user response:

here is the correct and easiest way to do it:

cls_labels = np.load('cls_labels.npy', allow_pickle = True).item()
  • Related