【发布时间】:2017-05-08 05:52:59
【问题描述】:
我有一个如下的 numpy 数组:
array([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
数组名为myArray,我对二维数组进行两次索引操作,得到如下结果:
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])
我对一个等效的数据框执行相同的操作序列:
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 相同的结果?
更新
如下所示,使用 b1.values 和 b2.values 有效,但现在当我构造函数并将其应用于 df 时,我不断收到 value 错误:
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 部分吗?
标签: python arrays pandas numpy dataframe