Load a .csv file into a numpy array as a column vector

时间:2016-08-31 18:33:13

标签: python arrays csv numpy

I've got a .csv file that I'm trying to load into a numpy array as a column vector. When using

temp = np.genfromtxt(location, delimiter=',')

the data is a numpy array where the entries are represented as follows:

[ 0.  ...  0.  1.  0.  ... 0.], [ 0.  ...  1.  0.  0.  ... 0.]

whereas, I would like something like this:

[array([[0],
       [0],
       [0],
       ...
       [0],
       [1],
       [0],
       ...
       [0],
       [0]]), array([[0], 
       [0],
       [0],
       ...
       [0],
       [1], 
       [0],
       ...)]

I'm able to accomplish this using

my_data = []

for i in range(len(temp)):
    foo = np.array([temp[i]]).T
    my_data.append(foo)

But am wondering if there is a more efficient way of achieving the required result.

1 个答案:

答案 0 :(得分:1)

Add a new axis to temp, and cast sublists to np arrays:

temp = np.genfromtxt(location, delimiter=',')
my_data = map(np.array, temp[:, :, np.newaxis])

For Python 3, call list on the above result or use a list comprehension:

my_data = [np.array(arr) for arr in temp[:, :, np.newaxis]]