user14655550
user14655550

Reputation:

why I cannot reshape or resize my numpy array

I have the following output for a

 [  1.   3.   5.   7.   9.  11.  13.  15.  17.  19.  21.  23.  25.  27.
    29.  31.  33.  35.  37.  39.  41.  43.  45.  47.  97.  99. 101. 103.
    105. 107. 109. 111. 113. 115. 117. 119. 121. 123. 125. 127. 129. 131.
    133. 135. 137. 139. 141. 143.]

I want to reshape it to the below

[[1.   3.   5.   7.   9.   11.  13.  15.]
 [17.  19.  21.  23.  25.  27.  29.  31.]
 [33.  35.  37.  39.  41.  43.  45.  47.]
 [97.  99. 101. 103.  105. 107. 109. 111.]
 [113. 115. 117. 119. 121. 123. 125. 127.]
 [129. 131. 133. 135. 137. 139. 141. 143.]]

I tried to use a.resize(6, 8), but it gives me this error: "resize only works on single-segment arrays" Also, when I am trying to use a.reshape(6, 8), it gives me the same array. I don't understand what is the reason for that as I have tested another array and worked well.

Upvotes: 1

Views: 6016

Answers (2)

Nadavo
Nadavo

Reputation: 250

Try

b = a.reshape((8,6))

and keep in mind 2 things, for future use of similar methods:

  1. the reshape method takes a tuple as input, in that case (8,6) , calling b = a.reshape(8,6) gives 2 int arguments to the method instead of the tuple it expects. always pay attention to the expected values. you can investigate that by just hovering over a function in pycharm and most editors.

  2. in numpy, many methods do not manipulate the given object but rather return a new value for you to use. it is healthy to always check for that in documentation, in order to avoid catastrophic heartbreaks, trust me.

Upvotes: 0

Hadar
Hadar

Reputation: 668

try a.reshape((8, 6)) notice the double parentheses

a = np.array([1., 3., 5., 7., 9., 11., 13., 15., 17., 19., 21., 23., 25., 27.,
              29., 31., 33., 35., 37., 39., 41., 43., 45., 47., 97., 99., 101., 103.,
              105., 107., 109., 111., 113., 115., 117., 119., 121., 123., 125., 127., 129., 131.,
              133., 135., 137., 139., 141., 143.])
print(a.reshape((8, 6)))

out:

[[  1.   3.   5.   7.   9.  11.]
 [ 13.  15.  17.  19.  21.  23.]
 [ 25.  27.  29.  31.  33.  35.]
 [ 37.  39.  41.  43.  45.  47.]
 [ 97.  99. 101. 103. 105. 107.]
 [109. 111. 113. 115. 117. 119.]
 [121. 123. 125. 127. 129. 131.]
 [133. 135. 137. 139. 141. 143.]]

Process finished with exit code 0

do notice that for the output you requested, the dimensions should be

a.reshape((6,8))

out:

[[  1.   3.   5.   7.   9.  11.  13.  15.]
 [ 17.  19.  21.  23.  25.  27.  29.  31.]
 [ 33.  35.  37.  39.  41.  43.  45.  47.]
 [ 97.  99. 101. 103. 105. 107. 109. 111.]
 [113. 115. 117. 119. 121. 123. 125. 127.]
 [129. 131. 133. 135. 137. 139. 141. 143.]]

Process finished with exit code 0

you can read about NumPy's reshape here: reshape documentation

Upvotes: 2

Related Questions