Python Forum

Full Version: Numpy reshape
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I tried to reshape a 3-D matrix using two different ways.
If the end result is 1-D the two methods match
If the end result is 2-D the two method fails

this code works
 a=np.random.randn(3,3,2)
b1 = a.reshape(1,-1).T
c1 = np.reshape(a,(-1,1))
This code doesn't work
 a=np.random.randn(3,3,2)
b1 = a.reshape(2,-1).T
c1 = np.reshape(a,(-1,2))
Output:
a array([[[-0.16364639, 1.18156333], [-1.39645684, 0.82572665], [ 0.49265179, -1.46054375]], [[-0.94382502, -0.22524816], [ 1.41986348, 2.0772036 ], [ 0.80148826, -1.24641239]], [[-0.09497732, 0.49188412], [ 0.00413193, -0.79643808], [ 0.09446335, -1.02043438]]]) b1 == c1 array([[ True, False], [False, False], [False, False], [False, False], [False, False], [False, False], [False, False], [False, False], [False, True]])
any explanation for that?
A simpler example
import numpy as np

a = np.array(range(6))
b = a.reshape(2,-1)   # First dimension is 2, second dimension is 3
c = a.reshape(-1, 2)  # First dimension is 3, second dimension is 2
bT = b.T

print("b", b, sep="\n")
print("bT", bT, sep="\n")
print("c", c, sep="\n")
Output:
b [[0 1 2] [3 4 5]] bT [[0 3] [1 4] [2 5]] c [[0 1] [2 3] [4 5]]
For bT == c to be True, the "rows" in b would have to be the same as the "columns" in c, and as you can see from the output this is not the case.

The reason your first example "works" is that the the single "row" in b is the same as the single "column" in c.
import numpy as np

a = np.array(range(6))
b = a.reshape(1,-1)
c = a.reshape(-1, 1)
bT = b.T

print("b", b, sep="\n")
print("bT", bT, sep="\n")
print("c", c, sep="\n")
Output:
b [[0 1 2 3 4 5]] bT [[0] [1] [2] [3] [4] [5]] c [[0] [1] [2] [3] [4] [5]]