Python 从查找数据帧列中减去数据帧列

Python 从查找数据帧列中减去数据帧列,python,pandas,dataframe,subtraction,lookup-tables,Python,Pandas,Dataframe,Subtraction,Lookup Tables,给定一个数据帧测试和另一个数据帧查找 test = pd.DataFrame( [['a',1], ['a',2], ['b',9]], columns = ['id', 'n']) lookup_mins = pd.DataFrame( [['a',1], ['b',9], ['c',

给定一个数据帧
测试
和另一个数据帧
查找

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

lookup_mins = pd.DataFrame( [['a',1], 
                             ['b',9], 
                             ['c',7]] , columns = ['id', 'n'])
尝试用
lookup\u mins
中匹配的
id
值减去
test
中的每个值
n

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\u mins
以获得上述预期结果?

与聚合
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
与聚合
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