Skip to main content
 首页 » 编程设计

python之比较 2 个数据帧以获得另一个数据帧

2024年10月01日6lonelyxmas

我在数据帧 df 上使用了 df.describe( ) 导致:

Index  count               mean          std           min            25%           max  
ABC       6                5.14         4.63             1              2            12 
CDE       6                18.6         12.5             2            7.5            15 
DEF       7                30.2         32.6             1            6.5            20 

另一个数据框df2

 Index              Date        eventName    eventCount 
 0            2017-08-09              ABC            24 
 1            2017-08-09              CDE           140 
 2            2017-08-10              CDE           150 
 3            2017-08-11              DEF           200 

threshold 列应计算为:

例如,对于 eventName:ABC 使用 date: 2017-08-09(daily) in dataframe df2 作为这个新数据帧中的新索引,偏差百分比对于日期:2017-08-09 要存储在这个新数据框中的值将是 eventCount 列中代表数据框 df2 中的 ABC 的值:这是 24 减去值dataframe df 中的 min 列也为 1 表示 ABC:24-1=23,然后除以 df2 中 ABC 的 eventCount 值 * ( 100), 即23/24*100=95%

生成的(新)数据框应如下所示:

     Index         eventName   eventCount        threshold       min 
2017-08-09               ABC           24        Under 95%         1 
2017-08-09               CDE          140      Under 98.5%         2 
2017-08-10               CDE          150      Under 99.3%         2 
2017-08-11               DEF          200      Under 99.5%         1  

我已经卡住了,我该怎么办?

请您参考如下方法:

使用join (默认 left)用于添加新列,然后进行一些算术运算:

df = df2.set_index('Date').join(df[['min']], on='eventName', how='left') 
df['threshold'] = df['eventCount'].sub(df['min']).div(df['eventCount']).mul(100).round(2) 
#if need preix with % 
df['threshold1'] =(df['eventCount'].sub(df['min']) 
                                   .div(df['eventCount']) 
                                   .mul(100) 
                                   .apply("Under {0:.2f}%".format)) 
print (df) 
 
           eventName  eventCount  min  threshold    threshold1 
Date                                                           
2017-08-09       ABC          24    1      95.83  Under 95.83% 
2017-08-09       CDE         140    2      98.57  Under 98.57% 
2017-08-10       CDE         150    2      98.67  Under 98.67% 
2017-08-11       DEF         200    1      99.50  Under 99.50%