0

I am trying to generate the output of the following Python statement with simple-enough-to-understand steps, possibly using for-loops. I have studied the .reshape method and what -1 means as a dimension. Here is a simplified code snippet:

import numpy as np
x = np.arange(6)in 
y = x**2
#-my attempt-/uncomment to see reosults-
#X =[[0, 0]]
#for i in np.araznge(1, 6):
#    X.append([[x[i],y[i]]])
#print(X)
#
#----------------------------
points = np.array([x, y]).T.reshape(-1, 1, 2)
print (points)
"""
# The output of the original statement, 
# which I would like to emulate is:

[[[ 0  0 ]]
 [[ 1  1 ]]
 [[ 2  4 ]]
 [[ 3  9 ]]
 [[ 4 16]]
 [[ 5 25]]]
 """

2 Answers2

0

I'm not exactly sure why you want your array to have shape (6, 1, 2), but you could certainly do something like;

result = np.empty((6, 1, 2), dtype=int)
result[:,0,0] = np.arange(6)
result[:,0,1] = result[:,0,0] ** 2

which sort of makes explicit what you're trying to do.

Frank Yellin
  • 9,127
  • 1
  • 12
  • 22
0

Ok, I solved my problem and here is the new look of the code:

import numpy as np
x = np.arange(0,6)
y = x**2 
points = np.array([x, y]).T.reshape(-1, 1, 2)
print("the original  ", type(points))
print (points)
#
#------my attempt----------------------
a = np.arange(0,6)
b = a**2
ab = [[[0, 0]]] 
for i in np.arange(1,6):
   ab.append(  [[  a[i]  ,  b[i]  ]])
ab =np. array(ab)   
print("\n my attempt  ",  type(ab))
print(ab)
#-------end my attept------------------
"""
the original   <class 'numpy.ndarray'>
[[[ 0  0]]
 [[ 1  1]]
 [[ 2  4]]
 [[ 3  9]]
 [[ 4 16]]
 [[ 5 25]]]

 my attempt   <class 'numpy.ndarray'>  ??
[[[ 0  0]]
 [[ 1  1]]
 [[ 2  4]]
 [[ 3  9]]
 [[ 4 16]]
 [[ 5 25]]]
[Program finished]
"""
  • @FrankYellin Your pythonic elequence is appreciated. I will spend some days to decipher it. It woked fine. – Turhan Tisinli Jul 24 '23 at 22:54
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 27 '23 at 09:50