Python Pandas-使用每行元素的点积创建新的DataFrame列

Python Pandas-使用每行元素的点积创建新的DataFrame列,python,pandas,dataframe,vectorization,dot-product,Python,Pandas,Dataframe,Vectorization,Dot Product,我试图获取一个现有的数据帧并附加一个新列 假设我有这个数据帧(只是一些随机数): 我想创建一个新的列“f”,它将每一行乘以一个“costs”向量,例如[1,0,0,0]。因此,对于第0行,f列中的输出应为2.847674 以下是我目前使用的函数: def addEstimate (df, costs): row_iterator = df.iterrows() for i, row in row_iterator: df.ix[i, 'f'] = np.dot(cos

我试图获取一个现有的数据帧并附加一个新列

假设我有这个数据帧(只是一些随机数):

我想创建一个新的列“f”,它将每一行乘以一个“costs”向量,例如[1,0,0,0]。因此,对于第0行,f列中的输出应为2.847674

以下是我目前使用的函数:

def addEstimate (df, costs): 
   row_iterator = df.iterrows()

   for i, row in row_iterator:
      df.ix[i, 'f'] = np.dot(costs, df.ix[i])
我用一个15个元素的向量,超过20k行,我发现这是一个超级重复的慢(半小时)。我怀疑使用
iterrows
ix
效率低下,但我不确定如何纠正这一点


有没有一种方法可以一次将其应用于整个数据帧,而不是通过行循环?或者您有其他建议来加速此过程吗?

您可以使用
df['f']=df.dot(costs)
创建新列

dot
已经是一种数据帧方法:将它作为一个整体应用于数据帧将比在数据帧上循环并将
np.dot
应用于单个行快得多

例如:

>>> df # an example DataFrame
    a   b   c   d   e
0   0   1   2   3   4
1  12  13  14  15  16
2  24  25  26  27  28
3  36  37  38  39  40

>>> costs = [1, 0, 0, 0, 2]
>>> df['f'] = df.dot(costs)
>>> df
    a   b   c   d   e    f
0   0   1   2   3   4    8
1  12  13  14  15  16   44
2  24  25  26  27  28   80
3  36  37  38  39  40  116

熊猫也有点功能。做

df['dotproduct'] = df.dot(costs)

你想干什么?

看来ajcr比我先干了!谢谢,这比我想象的要简单得多。
df['dotproduct'] = df.dot(costs)