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

Pandas实现df1中slope行1-5列值乘以df2对应Cost值的方法

解决方法

核心逻辑是先建立df2中「名称+分段」到成本值的映射关系,再匹配df1中的slope行对1-5列做数值乘法,完整可运行代码如下:

import pandas as pd
import numpy as np

# 构造示例df1
df1 = pd.DataFrame([
    ['Amazon', 1, 'slope', np.nan, 2.5, 2.5, 2.5, 2.5],
    ['Amazon', 1, 'x', 0.0, 1.0, 2.0, 3.0, 4.0],
    ['Amazon', 1, 'y', 0.0, 0.4, 0.8, 1.2, 1.6],
    ['Amazon', 2, 'slope', np.nan, 2.0, 2.0, 2.0, 2.0],
    ['Amazon', 2, 'x', 0.0, 2.0, 4.0, 6.0, 8.0],
    ['Amazon', 2, 'y', 0.0, 1.0, 2.0, 3.0, 4.0]
], columns=['Name', 'Segment', 'Axis', '1', '2', '3', '4', '5'])

# 构造示例df2
df2 = pd.DataFrame([
    ['Amazon', 1, 100],
    ['Amazon', 2, 112],
    ['Netflix', 1, 110],
    ['Netflix', 2, 210]
], columns=['Name', 'Segment', 'Cost'])

# 构建(Name, Segment)到Cost的映射字典
cost_map = df2.set_index(['Name', 'Segment'])['Cost'].to_dict()

# 筛选Axis为slope的行,对1-5列做乘法计算
df1.loc[df1['Axis'] == 'slope', ['1','2','3','4','5']] = df1[df1['Axis'] == 'slope'].apply(
    lambda row: row[['1','2','3','4','5']] * cost_map[(row['Name'], row['Segment'])],
    axis=1
)

print(df1)

运行输出结果和你预期的一致:

Name  Segment   Axis    1      2      3      4      5
0  Amazon        1  slope  NaN  250.0  250.0  250.0  250.0
1  Amazon        1      x  0.0    1.0    2.0    3.0    4.0
2  Amazon        1      y  0.0    0.4    0.8    1.2    1.6
3  Amazon        2  slope  NaN  224.0  224.0  224.0  224.0
4  Amazon        2      x  0.0    2.0    4.0    6.0    8.0
5  Amazon        2      y  0.0    1.0    2.0    3.0    4.0

如果你的1-5列是数值类型的列名(而非字符串类型),把代码里列名的引号去掉即可,其余逻辑无需调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 12:24:10