Pandas 基于条件的数据帧计算

Pandas dataframe calculation based on condition

我有两个数据帧,我需要使用 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

我需要使用这个公式来计算另一列:(Score(df) / Total(df_lb)) * 100

通常我可以对此类数据使用 if-else 条件,但我的数据很大,写数百 if_else 行会花费很多时间...我需要一种有效的方法吗?有没有?

在第二个 DataFrame 中使用 Series.map by Series by Brand 用于除以 Score 列并乘以 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设置为数据帧的索引并划分:

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