首页 > 解决方案 > 2个数据帧之间的条件行数

问题描述

我有以下2个数据框:

machine_id  time_to_failure
430494        1000
430494        700
430494        500
430494        100
430495        1000
430495        200

machine_id    event
430494        100
430494        600
430495        500
430495        100

我想在我的第一个 df 中添加第三个“count”列,该列计算第二个 df 中的行数event < time_to_failure。样本输出:

machine_id  time_to_failure  Count
430494        1000             2
430494        700              2
430494        500              1
430494        100              0
430495        1000             2
430495        200              1 

如何在不遍历行的情况下做到这一点?我试过了:

df1.insert(len(df1.columns), "Count", df2.loc[(df1.machine_id == df2.machine_id) &
                                              (df1.time_to_failure > df2.event)].count() )

但我收到了错误:

ValueError: Can only compare identically-labeled Series objects

我已经尝试过重置索引和检查对象类型。

标签: pythonpandasdataframecsv

解决方案


与广播的一个想法GroupBy.transform,选择另一个DataFrame,比较和求和True计数的值:

def f(x):
    y = df2.loc[df2['machine_id'].eq(x.name), 'event']
    return (x.to_numpy()[:, None] > y.to_numpy()).sum(axis=1)
    
df1['Count'] = df1.groupby('machine_id')['time_to_failure'].transform(f)
print (df1)
   machine_id  time_to_failure  Count
0      430494             1000      2
1      430494              700      2
2      430494              500      1
3      430494              100      0
4      430495             1000      2
5      430495              200      1

推荐阅读