我有两个数据框,分别代表从两个不同的计步器中提取的数据,这些计步器记录了一个人在特定月份跑步了多少英里。
我想为DF 1和DF 2中具有相同的“月份”和“人”的行计算“运行里程”中的差异。例如,DF 1和DF 2具有Joe在1月跑过的里程和Bob在2月跑过的里程。对于这两个常见行,我想计算两者的“ Miles Run”有多不同。
任何想法如何从具有2个匹配列值的两个DF中提取行?
DF 1:
Month of Year Miles Run Person
January 6.7458 Joe
February 1.3808 Bob
March 11.2689 Jill
April 9.8917 Sarah
DF 2:
Month of Year Miles Run Person
November 5.5234 Andrew
December 7.4523 Kyle
January 9.1189 Joe
February 7.4343 Bob
使用set_index
并让熊猫使用内部数据对齐执行减法:
(DF1.set_index(['Month of Year','Person']) - DF2.set_index(['Month of Year','Person'])).fillna(0)
输出:
Miles Run
Month of Year Person
April Sarah 0.0000
December Kyle 0.0000
February Bob -6.0535
January Joe -2.3731
March Jill 0.0000
November Andrew 0.0000
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句