首页 > 解决方案 > 在python中每五行相乘

问题描述

我有两个以下形式的熊猫数据框:

         df1                                  df2
                column                                 factor
             0    2                                0     0.0
             1    4                                1     0.25
             2    12                               2     0.50
             3    5                                3     0.99
             4    4                                4     1.00
             5    15
             6    32

工作是将df1中的每5行与df2相加,并将新结果放入df3(我的实际数据在df1中有大约500行)。结果应该是这样的:

        df3

            results     **description (no need to add this column)**
        0   15.95        df1.iloc[:4,0].dot(df2)
        1   24.46        df1.iloc[1:5,0].dot(df2)
        3   50.10        df1.iloc[2:6,0].dot(df2

标签: pythonpandas

解决方案


尝试:

import numpy as np

mx=df2.to_numpy()

df1.rolling(5).apply(lambda x: np.dot(x, mx), raw=True).iloc[4:]

输出:

   column
4   15.95
5   24.46
6   50.10

推荐阅读