Table t1
id mins maxs
0 43852 11 11
1 63087 14 15
2 63106 14 15
3 63155 14 15
Table t2
idx cons
0 1 1.00
1 2 0.95
2 3 0.90
3 4 0.85
4 5 0.80
5 6 0.70
6 7 0.70
7 8 0.65
8 9 0.60
9 10 0.55
10 11 0.50
11 12 0.45
12 13 0.40
13 14 0.35
14 15 0.35
15 16 0.30
我想对每个 id 的最小和最大范围内的缺点进行求和(idx 的最小和最大)
但出现以下错误:
error: an only compare identically-labeled Series objects
当我运行以下代码时:
t2.loc[(t2['idx']>= t1['mins']) & (t2['idx']<=t1['maxs']), 'cons'].sum()
我期待的是:
id mins maxs result
0 43852 11 11 0.50
1 63087 14 15 0.70
2 63106 14 15 0.70
3 63155 14 15 0.70
最佳答案
我会使用groupby.transform
在 t2
中搜索每对唯一的最小值/最大值:
t1['result'] = (t1
.groupby(['mins', 'maxs'])['id'] # column used here doesn't matter
.transform(lambda g: t2.loc[t2['idx'].between(g.name[0], g.name[1]),
'cons'].sum())
)
输出:
id mins maxs result
0 43852 11 11 0.5
1 63087 14 15 0.7
2 63106 14 15 0.7
3 63155 14 15 0.7
关于pandas - 基于两个数据帧的映射值(错误: an only compare identically-labeled Series objects),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75016291/