Python:将一个数据帧中的一列与另一个数据帧中的一列除以一个累加和

2024-10-01 04:56:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧,如下所示。我需要一个结果数据,它将python中的数据帧1的周期累计和除以在pin、site和department处索引的数据帧2的周期累计和。你知道吗

数据帧1:

 Pin    Site    Department   Period1     Period2     Period3     Period4

 1001     L       42           1           0           2           3
 1003     L       42           4           4           3           4
 1002     R       45           4           5           2           4                    

数据帧2:

Pin     Site    Department  Period1          Period2    Period3    Period4 

1002      R           45          5            6           5           5 
1003      L           42          4            5           6           8 
1001      L           42          1            2           4           5                    

输出

 Pin    Site    Department  Period1      Period2       Period3         Period4
 1001     L        42          1/1     (1+0)/(1+2)  (1+0+2)/(1+2+4) (1+0+2+3)/(1+2+4+5)
 1002     R        45          4/5     (4+5)/(5+6)  (4+5+2)/(5+6+5) (4+5+2+4)/(5+6+5+5)
 1003     L        42          4/4     (4+4)/(4+5)  (4+4+3)/(4+5+6) (4+4+3+4)/(4+5+6+8)

不管两个数据帧中管脚的顺序如何,我都需要如上所述的结果数据帧。周期数将逐月增加。你知道吗


Tags: 数据顺序pinsite管脚departmentperiod1period2
1条回答
网友
1楼 · 发布于 2024-10-01 04:56:10

我认为需要^{}将索引除以^{}^{}对齐,最后为MultiIndex中的列添加^{}

df11 = df1.set_index(['Pin','Site','Department']).cumsum(axis=1)
df22 = df2.set_index(['Pin','Site','Department']).cumsum(axis=1)

df = df11.div(df22).reset_index()
print (df)
    Pin Site  Department  Period1   Period2   Period3   Period4
0  1001    L          42      1.0  0.333333  0.428571  0.500000
1  1002    R          45      0.8  0.818182  0.687500  0.714286
2  1003    L          42      1.0  0.888889  0.733333  0.652174

编辑:

对于筛选出的值>1需要反转条件-保留值<=1-比较并检查每行是否有^{}True

df = df11.div(df22)
df = df[(df <= 1).all(axis=1)].reset_index()

相关问题 更多 >