Python 如何将numpy数组[(x1,y1),(x2,y2),(x3,y3),…(xn,yn)]转换为[(x1,y1,x1^2,y1^2),(x2,y2,x2^2,y2^2),…(xn,yn,xn^2,yn^2)]
我试过这个Python 如何将numpy数组[(x1,y1),(x2,y2),(x3,y3),…(xn,yn)]转换为[(x1,y1,x1^2,y1^2),(x2,y2,x2^2,y2^2),…(xn,yn,xn^2,yn^2)],python,numpy,Python,Numpy,我试过这个 x = np.array([ [0,0], [1,0], [2.61,-1.28], [-0.59,2.1] ]) for i in X: X = np.append(X[i], X[i][0]**2, axis = 1) print(X) 但我明白了 IndexError Traceback (most recent call last) <ipython-input-12
x = np.array([
[0,0],
[1,0],
[2.61,-1.28],
[-0.59,2.1]
])
for i in X:
X = np.append(X[i], X[i][0]**2, axis = 1)
print(X)
但我明白了
IndexError Traceback (most recent call last)
<ipython-input-12-9bfd33261d84> in <module>()
6 ])
7 for i in X:
----> 8 X = np.append(X[i], X[i][0]**2, axis = 1)
9
10 print(X)
IndexError: arrays used as indices must be of integer (or boolean) type
索引器错误回溯(最近一次调用)
在()
6 ])
7对于X中的i:
---->8 X=np.追加(X[i],X[i][0]**2,轴=1)
9
10份打印件(X)
索引器错误:用作索引的数组必须是整数(或布尔)类型
有人请帮忙 连接怎么样:
np.concatenate((x,x**2))
输出:
array([[ 0. , 0. ],
[ 1. , 0. ],
[ 2.61 , -1.28 ],
[-0.59 , 2.1 ],
[ 0. , 0. ],
[ 1. , 0. ],
[ 6.8121, 1.6384],
[ 0.3481, 4.41 ]])
连接如何:
np.concatenate((x,x**2))
输出:
array([[ 0. , 0. ],
[ 1. , 0. ],
[ 2.61 , -1.28 ],
[-0.59 , 2.1 ],
[ 0. , 0. ],
[ 1. , 0. ],
[ 6.8121, 1.6384],
[ 0.3481, 4.41 ]])
看一行:
In [214]: x[2]
Out[214]: array([ 2.61, -1.28])
您可以将该行与其正方形通过以下方式连接:
In [216]: np.concatenate((x[2], x[2]**2))
Out[216]: array([ 2.61 , -1.28 , 6.8121, 1.6384])
并对整个阵列执行相同的操作。尽可能在numpy
中使用整个数组,而不是行和元素。它更简单、更快
In [217]: np.concatenate((x, x**2), axis=1)
Out[217]:
array([[ 0. , 0. , 0. , 0. ],
[ 1. , 0. , 1. , 0. ],
[ 2.61 , -1.28 , 6.8121, 1.6384],
[-0.59 , 2.1 , 0.3481, 4.41 ]])
看一行:
In [214]: x[2]
Out[214]: array([ 2.61, -1.28])
您可以将该行与其正方形通过以下方式连接:
In [216]: np.concatenate((x[2], x[2]**2))
Out[216]: array([ 2.61 , -1.28 , 6.8121, 1.6384])
并对整个阵列执行相同的操作。尽可能在numpy
中使用整个数组,而不是行和元素。它更简单、更快
In [217]: np.concatenate((x, x**2), axis=1)
Out[217]:
array([[ 0. , 0. , 0. , 0. ],
[ 1. , 0. , 1. , 0. ],
[ 2.61 , -1.28 , 6.8121, 1.6384],
[-0.59 , 2.1 , 0.3481, 4.41 ]])
当您在列表上迭代时,例如使用列表中i的
打印(i)
,不要将该值用作索引,例如列表[i]
。我认为您需要阅读和练习基本Python。在交互式Python会话中进行练习,您可以在该会话中测试小块代码。哦,远离np.append
。这只会让您感到困惑。当您在列表上迭代时,例如使用列表中i的:print(i)
,不要将该值用作索引,例如alist[i]
。我认为您需要阅读和练习基本Python。在交互式Python会话中进行练习,您可以在该会话中测试小块代码。哦,远离np.append
。这只会让你困惑。