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

标签 python pandas dataframe vectorization dot-product

我正在尝试获取现有的 DataFrame 并附加一个新列。

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

    a           b           c            d          e
0   2.847674    0.890958    -1.785646   -0.648289   1.178657
1   -0.865278   0.696976    1.522485    -0.248514   1.004034
2   -2.229555   -0.037372   -1.380972   -0.880361   -0.532428
3   -0.057895   -2.193053   -0.691445   -0.588935   -0.883624

我想创建一个新列“f”,将每一行乘以“成本”向量,例如 [1,0,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 行)执行此操作,我发现这非常慢(半小时)。我怀疑使用 iterrowsix 效率低下,但我不知道如何纠正这个问题。

有没有一种方法可以立即将其应用于整个 DataFrame,而不是循环遍历行?或者您还有其他建议来加快速度吗?

最佳答案

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

dot 已经是一个 DataFrame 方法:将其作为一个整体应用于 DataFrame 比循环 DataFrame 并将 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

关于python - Pandas - 使用每行元素的点积创建新的 DataFrame 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28639551/

相关文章:

python - 使用 Pandas groupby agg 函数将集合转换为列表会导致 'ValueError: Function does not reduce'

如果在特定列中重复而其他列必须不同,则从 DF 中删除观察结果

java - H2OGeneralizedLinearEstimator() - 预测误差

python - 使用带有 IN 语句的 cx_Oracle (Python 3)

python - 如何使用经过训练的 tensorflow 算法

python - 当我设置 freq ="W"时,为什么输出变成 freq ="W-Sun"?

python - 在 Django View 中结合 modelformset 和 inlineformset

python - pandas.Grouper() 返回我的数据之外的分组日期标签

python - Pandas 面试问题 - 比较 Pandas-Joins 并理想地提供最快的方法

python - Pandas groupby 根据列值和组大小份额选择前 N 行