Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Numpy reshape
#1
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?
Reply
#2
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]]
mr_byte31 likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Reshape txt file into particular format using python shantanu97 0 1,440 Dec-10-2021, 11:44 AM
Last Post: shantanu97
  ValueError: Index contains duplicate entries, cannot reshapeā€¯ error when I try to use Smiling29 11 9,145 Oct-26-2019, 09:52 PM
Last Post: Smiling29

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020