首页 > 解决方案 > Calculate new column in pandas based on certain criteria

问题描述

I am trying to multiple a two df based on certain values.

data = {'a':10,'b':20,'c':30} . 

df1:

id,tag,factor
1,a ,20 
2,b ,22 
3,c ,25 

my final result should look like something below:

id,factor,calc  
1,20,200
2,22,440
3,24,750

The steps I have tried but giving error.

df['calc'] = df['factor'] * data.get(df['tag'])

标签: pythonpandas

解决方案


您可以使用pandas.Series.mappandas.DataFrame.drop

df['calc'] = df['factor'] * df['tag'].map(data)
df.drop('tag', axis=1, inplace=True)

输出:

   id  factor  calc
0   1      20   200
1   2      22   440
2   3      25   750

推荐阅读