[英]How to convert a numpy array [(x1,y1),(x2,y2),(x3,y3),…(xn,yn)] to [(x1,y1,x1^2,y1^2),(x2,y2,x2^2,y2^2),…(xn,yn,xn^2,yn^2)]
I tried this我试过这个
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)
But i am getting this但我得到了这个
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
Someone please help!有人请帮忙!
How about concatenate:如何连接:
np.concatenate((x,x**2))
Output: Output:
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 [210]: x = np.array([
...: [0,0],
...: [1,0],
...: [2.61,-1.28],
...: [-0.59,2.1]
...: ])
...:
In [211]: x # (4,2) array
Out[211]:
array([[ 0. , 0. ],
[ 1. , 0. ],
[ 2.61, -1.28],
[-0.59, 2.1 ]])
In [212]: for i in x: # iterate on rows
...: print(i) # i is a row, not an index x[i] would be wrong
...:
[0. 0.]
[1. 0.]
[ 2.61 -1.28]
[-0.59 2.1 ]
Look at one row:看一行:
In [214]: x[2]
Out[214]: array([ 2.61, -1.28])
You can join that row with its square with:您可以将该行与其正方形连接:
In [216]: np.concatenate((x[2], x[2]**2))
Out[216]: array([ 2.61 , -1.28 , 6.8121, 1.6384])
And doing the same for the whole array.并对整个阵列做同样的事情。 Where possible in numpy
work with the whole array, not rows and elements.在numpy
中尽可能使用整个数组,而不是行和元素。 It's simpler, and faster.它更简单,更快。
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 ]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.