python - 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
我已经尝试过重置索引和检查对象类型。
解决方案
与广播的一个想法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
推荐阅读
- arrays - 切割排序切片的最佳方法
- json - 使用 PySpark 从 Cloudera CDSW 项目中读取文件
- android - 将图像从列表视图传递到另一个活动
- javascript - 如何使用 SAP Leonardo 的 API 翻译?
- c++ - 您应该在模板代码中完全避免使用 const 吗?
- kubernetes - 如何将文件从一个命名空间中的 pod 复制到另一个命名空间中的 pod
- javascript - 需要对一些基本设置进行一些说明
- c - 获取进程返回 -1073741819 (0xC0000005) 错误而不是回答
- ios - 我无法在我的 iOS 设备上运行我的应用程序,即使它们已更新
- vue.js - 如何使用 vue-paypal-checkout 生成项目列表?