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

如何在Pandas中实现成本价格按系数相乘后追加到DataFrame末尾?

如何基于颜色调整系数生成新行并追加到Pandas DataFrame?

我现在有这样一个Pandas DataFrame:

import pandas as pd

df = pd.DataFrame({
    'Colour': ['Red', 'Blue', 'Blue', 'Green', 'Yellow'],
    'Type': ['Car', 'Bike', 'Car', 'Bike', 'Bike'],
    'Cost': [3, 6, 4, 6, 3],
    'Price': [5, 7, 8, 9, 3],
    'Type': ['Standard', 'Standard', 'Standard', 'Standard', 'Standard']
})

还有一个颜色调整系数的Series:

adjustment = pd.Series([2, 1, 3], index=['Red', 'Blue', 'Green'])

我的需求是:把对应颜色的Cost和Price字段分别乘以对应的调整系数,生成新的行,这些新行的最后一列Type值改为Adjusted,然后把这些新行追加到原DataFrame的末尾,得到预期的输出。现在我有点困惑,想找一个简便的实现方法。


嗨,这个需求其实很容易搞定,咱们一步步来操作:

先提个小建议:处理重复列名

首先注意到你的DataFrame里有两个Type列,这会给后续操作添不少麻烦,建议先把最后一列重命名成更清晰的名称,比如Status:

df.columns = ['Colour', 'VehicleType', 'Cost', 'Price', 'Status']

当然如果坚持要用原列名也可以,但后续得靠位置索引(比如iloc[:, -1])来操作,重命名显然更稳妥。

生成调整后的新数据

咱们先复制一份原数据,然后通过颜色匹配调整系数,批量修改Cost和Price,最后把状态改成Adjusted:

# 复制原DataFrame
adjusted_df = df.copy()

# 用map匹配对应颜色的系数,没匹配到的(比如Yellow)默认乘1保持原值
adjustment_coeff = adjusted_df['Colour'].map(adjustment).fillna(1)

# 批量调整Cost和Price
adjusted_df['Cost'] = adjusted_df['Cost'] * adjustment_coeff
adjusted_df['Price'] = adjusted_df['Price'] * adjustment_coeff

# 修改状态为Adjusted
adjusted_df['Status'] = 'Adjusted'

合并原数据与调整后的数据

最后用pd.concat把两个DataFrame拼在一起就大功告成了:

final_df = pd.concat([df, adjusted_df], ignore_index=True)

如果不想修改列名的完整代码

要是你不想改动原列名,针对重复的Type列可以这么写:

import pandas as pd

# 原始数据
df = pd.DataFrame({
    'Colour': ['Red', 'Blue', 'Blue', 'Green', 'Yellow'],
    'Type': ['Car', 'Bike', 'Car', 'Bike', 'Bike'],
    'Cost': [3, 6, 4, 6, 3],
    'Price': [5, 7, 8, 9, 3],
    'Type': ['Standard', 'Standard', 'Standard', 'Standard', 'Standard']
})

# 调整系数
adjustment = pd.Series([2, 1, 3], index=['Red', 'Blue', 'Green'])

# 复制并调整数据
adjusted_df = df.copy()
coeff = adjusted_df['Colour'].map(adjustment).fillna(1)
adjusted_df['Cost'] *= coeff
adjusted_df['Price'] *= coeff
# 修改最后一列Type为Adjusted
adjusted_df.iloc[:, -1] = 'Adjusted'

# 合并两个DataFrame,保留原索引和你的示例一致
final_df = pd.concat([df, adjusted_df], ignore_index=False)

这样得到的结果就和你预期的完全一致啦!关键是利用map方法快速匹配颜色对应的系数,批量处理比逐行循环高效得多,最后合并数据也很直观。

内容的提问来源于stack exchange,提问作者fred.schwartz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 23:02:45