47

I have a large list files that contain 2D numpy arrays pickled through numpy.save. I am trying to read the first column of each file and create a new 2D array.

I currently read each column using numpy.load with a mmap. The 1D arrays are now in a list.

col_list = []
for f in file_list:
    Temp = np.load(f,mmap_mode='r')
    col_list.append(Temp[:,0])

How can I convert this into a 2D array?

3 Answers 3

73

You can use

numpy.stack(arrays, axis=0)

if you have an array of arrays. You can specify the axis in case you want to stack columns and not rows.

Sign up to request clarification or add additional context in comments.

1 Comment

This should be the selected answer, or at least ranked higher. The regular way (with nd.array) doesn't work with lists of ndarrays
28

The array may be recreated:

a = np.array(a.tolist())

2 Comments

This answer needn't be downvoted, it works in instances when @senshin 's answer won't work.
This answer is only useful when you have an array of arrays, which is not a list of arrays.
24

You can just call np.array on the list of 1D arrays.

>>> import numpy as np
>>> arrs = [np.array([1,2,3]), np.array([4,5,6]), np.array([7,8,9])]
>>> arrs
[array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])]
>>> arr2d = np.array(arrs)
>>> arr2d.shape
(3, 3)
>>> arr2d
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

3 Comments

Thanks this works great. Since I wanted columns instead of rows I did have to do some transposes and optimize the direction of the data collection, but it works great.
THis does not work for multidimensional array. Any solution to that?
Note that this doesn't work for lists of ndarrays. For a cleaner solution see the answer below using np.stack

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.