Pandas 从查找 DataFrame 列中减去 DataFrame 列

问题描述

给定一个数据框 test 和另一个数据框 lookup

test = pd.DataFrame( [['a',1],['a',2],['b',9]],columns = ['id','n'])

lookup_mins = pd.DataFrame( [['a',9],['c',7]],'n'])

尝试用 n 中的值 test 减去 n 中的每个值 id 并使用 lookup_mins 中的匹配 s = lookup_mins.groupby(['id'])['n'].transform('min') test['n2'] = test['n'] - s 使用

id n n2
a  1 0
a  2 1
b  9 0

预期结果,

id n n2
a  1 0
a  2 -7
b  9  9

反而得到了

test

如何减去 lookup_minsLcounterCar,LcounterTruck,LcounterBus,LcounterMotorcycle,LcounterVan,Ltime,RcounterCar,RcounterTruck,RcounterBus,RcounterMotorcycle,RcounterVan,Rtime 1,2021-02-22 13:22:00,2,2021-02-22 13:23:00,3,1,4,2021-02-22 13:24:00,5,2021-02-22 13:25:00,6,2021-02-22 13:27:00 以获得如上所述的预期结果?

解决方法

Series.map 与聚合 min 一起使用:

s = lookup_mins.groupby(['id'])['n'].min()
test['n2'] = test['n'] - test['id'].map(s)
print (test)
  id  n  n2
0  a  1   0
1  a  2   1
2  b  9   0