如何根据另外两个列的值设置列?

问题描述 投票:0回答:1

我有一个总计字典:

totals = {('china', 1990): 12345, ('china', 1999): 6789, ('mexico', 1989): 98765}

和数据框df

country   year
china     1990
china     1999
mexico    1989
....

我想根据上面的词典添加totals的新列。我已经尝试过了,但是不起作用:

df['total'] = df[['country', 'year']].apply(lambda x: totals[x])

什么是正确的方法?

pandas
1个回答
0
投票

用途:

df['total'] = df.set_index(['country', 'year']).index.map(totals)
© www.soinside.com 2019 - 2024. All rights reserved.