You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas函数中传入列名实现按列与字典值相乘?

解决方法

方法1:修正apply调用(兼容你的自定义函数)

你原来的代码错误使用了x.column,Series对象的列名属性是name。当df.apply默认按列(axis=0)处理时,每个传入lambda的x是对应列的Series,x.name就是商品名称(列名),修正后的调用如下:

import pandas as pd

df = pd.DataFrame({'banana': [1, 8], 'apple': [3, 6]}, index=['2023-01-01', '2023-01-02'])
price_dict = {'banana': 10, 'apple': 100}

def get_sales(quantity, fruit):
    return price_dict[fruit] * quantity

# 修正后的apply调用
df_sales = df.apply(lambda x: get_sales(x, x.name))
print(df_sales)

输出结果:

banana  apple
2023-01-01       10    300
2023-01-02       80    600

方法2:更高效的向量化操作(推荐)

不需要自定义函数,直接利用pandas的广播特性,将价格字典转为Series后与原DataFrame相乘,这种方法比apply的循环操作效率高得多,适合大数据量场景:

import pandas as pd

df = pd.DataFrame({'banana': [1, 8], 'apple': [3, 6]}, index=['2023-01-01', '2023-01-02'])
price_dict = {'banana': 10, 'apple': 100}

# 将价格字典转为Series,自动匹配列名
price_series = pd.Series(price_dict)
df_sales = df * price_series
print(df_sales)

输出结果和上面一致。


内容的提问来源于stack exchange,提问作者Filledille

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 05:30:47