我正在尝试使用足够简单易懂的步骤(可能使用 for 循环)生成以下 Python 语句的输出。我研究了 .reshape 方法以及 -1 作为维度的含义。这是一个简化的代码片段:
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]]]
"""
我不太确定为什么你希望你的数组具有形状 (6, 1, 2),但你当然可以这样做;
result = np.empty((6, 1, 2), dtype=int)
result[:,0,0] = np.arange(6)
result[:,0,1] = result[:,0,0] ** 2
这可以明确你想要做什么。
好的,我解决了我的问题,这是代码的新外观:
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]
"""