Skip to main content
 首页 » 编程设计

python之使用应用于数据框中每一列的多个参数的自定义函数

2025年01月19日14mengfanrong

我有一个看起来像这样的 df

data =  [{'Stock': 'Apple', 'Weight': 0.2, 'Price': 101.99, 'Beta': 1.1}, 
         {'Stock': 'MCSFT', 'Weight': 0.1, 'Price': 143.12, 'Beta': 0.9}, 
         {'Stock': 'WARNER','Weight': 0.15,'Price': 76.12,  'Beta': -1.1}, 
         {'Stock': 'ASOS',  'Weight': 0.35,'Price': 76.12,  'Beta': -1.1 }, 
         {'Stock': 'TESCO', 'Weight': 0.2, 'Price': 76.12,  'Beta': -1.1 }] 
data_df = pd.DataFrame(data) 

和一个将计算加权平均值的自定义函数

def calc_weighted_averages(data_in, weighted_by): 
    return sum(x * y for x, y in zip(data_in, weighted_by)) / sum(weighted_by) 

我想将此自定义公式应用于我的 df 中的所有列,我的第一个想法是做某事。像这样

data_df = data_df[['Weight','Price','Beta']] 
data_df = data_df.apply(lambda x: calc_weighted_averages(x['Price'], x['Weight']), axis=1) 

如何固定我的 weighted_by 列并将自定义函数应用于其他列?我最终应该得到价格和 Beta 的加权平均数。

请您参考如下方法:

我认为您首先需要所有列的子集,然后使用第二个参数权重列:

s1 = data_df[['Price','Beta']].apply(lambda x: calc_weighted_averages(x, data_df['Weight'])) 
print (s1) 
Price    87.994 
Beta     -0.460 
dtype: float64 

没有 apply 的另一种解决方案更快:

s1 = data_df[['Price','Beta']].mul(data_df['Weight'], 0).sum().div(data_df['Weight'].sum()) 
print (s1) 
Price    87.994 
Beta     -0.460 
dtype: float64