Reputation: 49
I have a numpy array called "all_runs" that is comprised of hundreds of np arrays I appended together in a function. Here is an example of what it looks like when I append two arrays:
[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]
I want to reshape this to the following:
0 1 2
0 1 2
0 1 2
0 1 2
0 1 2
0 1 2
0 1 2
0 1 2
I have tried this:
df = pd.DataFrame(all_runs.reshape(3, 8))
but it is not giving the result I want:
0 0 0
0 1 1
1 1 2
2 2 2
0 0 0
0 1 1
1 1 2
2 2 2
Is there an efficient way to split the array and reshape it in the format shown above?
Upvotes: 0
Views: 322
Reputation: 1251
In one line:
a = np.array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2])
print(np.vstack(np.hsplit(a.reshape(6,4).transpose(),2)))
Output:
[[0 1 2]
[0 1 2]
[0 1 2]
[0 1 2]
[0 1 2]
[0 1 2]
[0 1 2]
[0 1 2]]
Upvotes: 1
Reputation: 159
Sort your array and then reshape it as.
import numpy as np
test = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]
test = np.asarray(test)
np.sort().reshape(3,8)
Output
array([[0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1],
[2, 2, 2, 2, 2, 2, 2, 2]])
Upvotes: 0
Reputation: 10590
You may be better off creating your array differently, so you don't have to reshape your array. It might be simpler to format your array into its shape when creating it rather than appending then reshaping.
Regardless, you have to consider order of the axes when reshaping. It ends up being somewhat convoluted, but you could try this:
arr = np.array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2])
np.vstack(arr.reshape([2, -1]).reshape(2, 3, -1).transpose([0, 2, 1]))
Output:
array([[0, 1, 2],
[0, 1, 2],
[0, 1, 2],
[0, 1, 2],
[0, 1, 2],
[0, 1, 2],
[0, 1, 2],
[0, 1, 2]])
Upvotes: 0