3

I know how to save an array of simple data (like float type values) to a file using numpy.save and numpy.savez.

I also know how to save a single object to a file using the pickle module, although I have not tested it yet.

The question is: How can I save (and load) an array of objects to a file? Can I combine the two methods exposed above in order to achieve this? Is there a better way?

Aeryan
  • 43
  • 1
  • 4
  • https://stackoverflow.com/a/32850511/3923163 – cwalvoort Oct 06 '19 at 21:20
  • What's the shape and dtype of that array of objects? Have you tried `np.save`? To load it you may need to use the `allow_pickle` parameter. Read the docs for both `save` and `load`. – hpaulj Oct 06 '19 at 21:36
  • You can create a list of objects. List is a single object. You know how to save a single object with pickle :) – sanyassh Oct 06 '19 at 22:33
  • @hpaulj the shape would be (-1, 3) (array of triplets) and I forgot that every element of the triplet is of a different type (class A, int, class B), so I think I shouldn't use numpy arrays but rather normal python lists. – Aeryan Oct 07 '19 at 14:33
  • @sanyash didn't think about that. I suppose I can order my data as a list of triplets (lists) where each element is an object. This way the whole data structure will be a Python list and I should be able to save it using the pickle module. I'll try it and update the question with my results. Thanks in advance! :) – Aeryan Oct 07 '19 at 14:37
  • @sanyash I tested it and it works! I pack all my data into a single Python array and save and load it using the pickle module with no problems at all. Please, post your comment as an answer so that I can accept it and close the question. – Aeryan Oct 08 '19 at 15:40

1 Answers1

1

If you know how to pickle a single object, to pickle some amount of objects you can create a structure that contains all these objects (list, set, dict with these objects as values for example, or your own class which contains them in some way) and this structure will be a single object awailable to pickle.

sanyassh
  • 8,100
  • 13
  • 36
  • 70