Skip to main content
 首页 » 编程设计

python之按列值比较两个 Pandas 数据框的行

2024年10月01日7jackei

我有两个数据框,它们代表从两个不同的计步器中提取的数据,这些计步器记录了给定的人在特定月份跑了多少英里。

我想计算 DF 1 和 DF 2 中具有相同“Month of Year”和“Person”的行的“Miles Run”差异。例如,DF 1 和 DF 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 并让 Pandas 使用内部数据对齐来执行减法:

(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