用python划分两个数据帧
我有两个数据帧:用python划分两个数据帧,python,pandas,dataframe,multiple-columns,division,Python,Pandas,Dataframe,Multiple Columns,Division,我有两个数据帧:df1和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的所有列,
df1
和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)
有什么想法吗?如果
时间戳
不是索引,这应该可以:
>>> 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())
您可以从两列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
是的,我假设
时间戳
是索引。是的,如果它的第一列是索引
,则解决方案更简单df3=df1.div(df2)
@jezrael thak谢谢你的回复,但我犯了一个错误,你能检查我的帖子编辑吗?谢谢谢谢Alexander,但是我犯了一个错误,你能检查我的帖子编辑吗?非常感谢。