Question
I am having trouble identifying objects numpy.int64in order to convert them to a basic python int for json serialization. isinstanceusually works, but not in the following example, and I would like to understand why this is so.
>>> x
0
>>> type(x)
<class 'numpy.int64'>
>>> import numpy
>>> isinstance(x, numpy.int64)
False
context
x in the example above comes from my application generated to_dicton a pandas data frame. Various data frames are used to generate the result, so I cannot just use pandas to_json.
taking hints from How to identify numpy types in python? I really managed to successfully detect these elements (which are sometimes not numpy objects) using the following:
>>> (isinstance(x, (pd.np.ndarray, pd.np.generic)) and
>>> pd.np.issubdtype(x, pd.np.dtype('int64')))
True
, - , , , . simplejson JSONDecoder, isinstance(obj, pd.np.int64), , .
pickle.dumps(x) b'\x80\x03cnumpy.core.multiarray\nscalar\nq\x00cnumpy\ndtype\nq\x01X\x02\x00\x00\x00i8q\x02K\x00K\x01\x87q\x03Rq\x04(K\x03X\x01\x00\x00\x00<q\x05NNNJ\xff\xff\xff\xffJ\xff\xff\xff\xffK\x00tq\x06bC\x08\x00\x00\x00\x00\x00\x00\x00\x00q\x07\x86q\x08Rq\t.'
, , , .
>>> isinstance(pickle.loads(pickle.dumps(x)), pd.np.int64)
True