NumPy - IO

Updated: 2018-12-04

Read

Read As NumPy Array

data = np.loadtxt("../input/train.csv", delimiter=",", skiprows=1)

Write

Python list can be directly dumped as JSON

>>> a = [1,2,3]
>>> json.dumps(a)
'[1, 2, 3]'

However numpy array can not:

>>> import numpy as np
>>> a = np.array([1,2,3])
>>> a
array([1, 2, 3])
>>> json.dumps(a)
Traceback (most recent call last):
    ...
TypeError: array([1, 2, 3]) is not JSON serializable

And converting it to list does not work:

>>> json.dumps(list(a))
Traceback (most recent call last):
  ...
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: 1 is not JSON serializable

Instead use .tolist()

>>> json.dumps(a.tolist())
'[1, 2, 3]'