Python 基于条件的数据帧计算

Python 基于条件的数据帧计算,python,pandas,function,calculation,Python,Pandas,Function,Calculation,我有两个dataframe,我需要使用1作为参考来计算其他值 例如,我有这样的df: Brand LB_ID Score BMW Class 98 BMW Cost 99 VW Class 85 VW Cost 70 另一个df_lb像这样 Brand Total BMW 56 VW 180 我需要使用这个公式来计算另一列:(分数(df)/Tot

我有两个dataframe,我需要使用1作为参考来计算其他值

例如,我有这样的
df

Brand    LB_ID       Score
BMW      Class       98
BMW      Cost        99
VW       Class       85
VW       Cost        70
另一个
df_lb
像这样

Brand     Total
BMW       56
VW        180
我需要使用这个公式来计算另一列:
(分数(df)/Total(df_lb))*100

通常我可以使用if-else条件来处理这些数据,但我有大数据,写几百行if-else需要很多时间。。。我需要一个有效的方法?是否有?

用于新的
系列
by
品牌
的第二个数据帧,用于除以
得分
列,用于新列的乘以
100

df['new'] = df['Score'].div(df['Brand'].map(df_lb.set_index('Brand')['Total'])).mul(100)
print (df)
  Brand  LB_ID  Score         new
0   BMW  Class     98  175.000000
1   BMW   Cost     99  176.785714
2    VW  Class     85   47.222222
3    VW   Cost     70   38.888889
先合并

m = df.merge(df_lb)
然后计算新列

m['new'] = 100 * m['Score'] / m['Total']

Brand
设置为数据帧和divide的索引:

df["new"] = (df.set_index("Brand")
               .Score
               .div(df_lb.set_index("Brand").Total)
              .mul(100)
              .array)

df


   Brand    LB_ID   Score   new
0   BMW     Class   98  175.000000
1   BMW     Cost    99  176.785714
2   VW      Class   85  47.222222
3   VW      Cost    70  38.888889

如果没有匹配,可能吗?那会发生什么?