我试图从我的数据帧的每一行中减去一个向量。我正在Windows 3上使用Python 3和Anaconda。

这是我拥有的数据帧:

数据框1(1行,5列):

    Col1  Col2  Col3  Col4  Col5
45  94.0    94  92.0    90    86


数据框2(17981行,5列):

   Col1  Col2  Col3  Col4  Col5
0  85.0    98  78.0    74    20
1  74.1    87  34.0    85    15
..  ...   ...   ...   ...   ...


最初,我尝试将一个向量减去另一个向量,但发现自己遇到多个NAN,之后尝试并遵循this question

df1 = df1.iloc[0,:]
df2.sub(df1)


但我仍然收到错误消息:

ValueError: can only convert an array of size 1 to a Python scalar


谁能帮助我并指出我需要做什么?

附加说明,两个数据框的形状为:

df1 = (5,)
df2 = (17981,5)

最佳答案

In [134]: d2.sub(d1.iloc[0], axis=1)
Out[134]:
   Col1  Col2  Col3  Col4  Col5
0  -9.0   4.0 -14.0 -16.0 -66.0
1 -19.9  -7.0 -58.0  -5.0 -71.0


要么:

In [135]: d2 - d1.iloc[0].values
Out[135]:
   Col1  Col2  Col3  Col4  Col5
0  -9.0   4.0 -14.0 -16.0 -66.0
1 -19.9  -7.0 -58.0  -5.0 -71.0

关于python - 将向量减去每行数据框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48271643/

10-12 16:47
查看更多