0

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.

3
  • 1
    Do you specifically want the items in the list to be arrays? Otherwise, you can do: temp[:, :, None].tolist() Commented Aug 31, 2016 at 18:38
  • Do you want the array to be in a list or is that a typo? Commented Aug 31, 2016 at 18:47
  • It would be better is the items in the list were arrays, that way I wouldn't need to make alterations to my main code Commented Aug 31, 2016 at 18:48

1 Answer 1

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

list(temp[...,None]) does the same thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.