我有一个numpy的阵列如下:应用上熊猫数据帧numpy的功能
array([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
阵列被名为myArray,我执行2D阵列上的两个索引操作,并得到如下结果:
In[1]: a2 = myArray[1:]
a2
Out[1]:array([[3, 4],
[5, 6],
[7, 8]])
In[2]: a1 = myArray[:-1]
a1
Out[2]:array([[1, 2],
[3, 4],
[5, 6]])
现在,我执行numpy的功能得到如下结果:
In[]: theta = np.arccos((a1*a2).sum(axis= 1)/(np.sqrt((a1**2).sum(axis= 1)*(a2**2).sum(axis= 1))))
theta
Out[]: array([ 0.1798535 , 0.05123717, 0.02409172])
我执行SA我一个等效的数据帧顺序操作:
In[]: df = pd.DataFrame(data = myArray, columns = ["x", "y"])
df
Out[]:
x y
0 1 2
1 3 4
3 5 6
4 7 8
In[]: b2 = df[["x", "y"]].iloc[1:]
Out[]: b2
x y
1 3 4
2 5 6
3 7 8
In[]: b1 = df[["x", "y"]].iloc[:-1]
b1
Out[]:
x y
0 1 2
1 3 4
2 5 6
但现在,当我试图让THETA的数据帧,我只得到0和NaN值
In[]: theta2 = np.arccos((b1*b2).sum(axis= 1)/(np.sqrt((b1**2).sum(axis= 1)*(b2**2).sum(axis= 1))))
theta2
Out[]:
0 NaN
1 0.0
2 0.0
3 NaN
dtype: float64
它是正确的我正在应用numpy函数索引数据帧?将数据框应用于theta时应如何得到相同的结果?
UPDATE
如下建议,使用b1.values和b2.values的作品,但现在当我在构造函数,并把它应用到东风,我不断收到价值的错误:
def theta(group):
b2 = df[["x", "y"]].iloc[1:]
b1 = df[["x", "y"]].iloc[:-1]
t = np.arccos((b1.values*b2.values).sum(axis= 1)/
(np.sqrt((b1.values**2).sum(axis= 1)*(b2.values**2).sum(axis= 1))))
return t
df2 = df.apply(theta)
这给ValueError异常
ValueError: Shape of passed values is (2, 3), indices imply (2, 4)
请让我知道我错了。
在此先感谢。
@ piRSquared你能否帮我解决** UPDATE **部分。 – Liza