用Python分割两个数据框。

7

I have two dataframes : df1 and df2

df1:

TIMESTAMP           eq1 eq2 eq3
2016-05-10 13:20:00  40  30  10
2016-05-10 13:40:00  40  10  20

df2:

TIMESTAMP           eq1 eq2 eq3
2016-05-10 13:20:00  10  20  30
2016-05-10 13:40:00  10  20  20

我希望将df1除以df2,即将df1的每一列都除以df2的所有列,得到结果df3

TIMESTAMP           eq1        eq2        eq3
2016-05-10 13:20:00  40/(10+10) 30/(20+20) 10/(30+20)
2016-05-10 13:40:00  40/(10+10) 10/(20+20) 20/(30+20)

请问有什么想法吗?
2个回答

8
您可以使用 div 函数,但是在使用之前需要先使用 set_index 函数并将两个列 TIMESTAMP 作为索引:
df1.set_index('TIMESTAMP', inplace=True)
df2.set_index('TIMESTAMP', inplace=True)

print (df1.div(df2).reset_index())
            TIMESTAMP  eq1  eq2       eq3
0 2016-05-10 13:20:00  4.0  1.5  0.333333
1 2016-05-10 13:40:00  4.0  0.5  1.000000

评论编辑:

df1.set_index('TIMESTAMP', inplace=True)
df2.set_index('TIMESTAMP', inplace=True)
print (df2.sum())
eq1    20
eq2    40
eq3    50
dtype: int64

print (df1.div(df2.sum()).reset_index())
            TIMESTAMP  eq1   eq2  eq3
0 2016-05-10 13:20:00  2.0  0.75  0.2
1 2016-05-10 13:40:00  2.0  0.25  0.4

是的,我曾经认为TIMESTAMP是索引。 - Alexander
是的,如果第一列是“索引(indexes)”,那么解决方案就更简单了,即df3 = df1.div(df2) - jezrael
@jezrael 谢谢您的回复,但我犯了一个错误,请您帮忙检查一下我的帖子编辑吗?谢谢。 - Poisson

2

如果TIMESTAMP不是索引,那么这应该可以工作:

>>> df1.set_index('TIMESTAMP').div(df2.set_index('TIMESTAMP').sum()) 
                     eq1   eq2  eq3
TIMESTAMP                          
2016-05-10 13:20:00    2  0.75  0.2
2016-05-10 13:40:00    2  0.25  0.4

如果TIMESTAMP是索引,那么只需这样做:
df1.div(df2.sum()) 

谢谢你,亚历山大。但是我犯了一个错误,你能帮我检查一下我的帖子编辑吗?谢谢。 - Poisson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接