pandas - 基于两个数据帧的映射值(错误: an only compare identically-labeled Series objects)

标签 pandas dataframe pandas-loc

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.transformt2 中搜索每对唯一的最小值/最大值:

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/

相关文章:

python - 在列中拆分 Pandas 数据框值?

python - 根据子字符串拆分列表元素

pandas - 如何基于列内爆( Pandas 的反向 explode )

python - 如何访问 pandas 数据框中前几行的数据?

python - Pandas Apply 和 Loc - 效率和索引

python - 根据条件提取列值

Python:如何根据第一列中的值将 pandas DataFrame 拆分为子集?

python - Pandas 删除列多索引中的空白行

r - 如何提取具有正值和负值的相同行

python - 从 pandas Dataframe 中删除重复数据