Reputation: 9
I have a numpy array called 'results' which is defined like this
array([1, 2, 3, 4, 5, 6])
but I need it to look like this:
array([1, 2], [3, 4], [5, 6])
How can I convert 'results' into this new array in Python? The array I end up with still needs to be a numpy array.
Upvotes: 1
Views: 2098
Reputation: 10224
You can achieve this directly by using the reshape
method.
For example:
In [1]: import numpy as np
In [2]: arr = np.array([1, 2, 3, 4, 5, 6])
In [3]: reshaped = arr.reshape((3, 2))
In [4]: reshaped
Out[4]:
array([[1, 2],
[3, 4],
[5, 6]])
Note that where possible, reshape
will give you a view of the array. In other words, you're looking at the same underlying data as for the original array:
In [5]: reshaped[0][0] = 7
In [6]: reshaped
Out[6]:
array([[7, 2],
[3, 4],
[5, 6]])
In [7]: arr
Out[7]: array([7, 2, 3, 4, 5, 6])
This is almost always an advantage. However, if you don't want this behaviour, you can always take a copy:
In [8]: copy = np.copy(reshaped)
In [9]: copy[0][0] = 9
In [10]: copy
Out[10]:
array([[9, 2],
[3, 4],
[5, 6]])
In [11]: reshaped
Out[11]:
array([[7, 2],
[3, 4],
[5, 6]])
Upvotes: 5