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

如何用Pandas新增PriceError和CostError列(基于指定列与阈值)

Adding PriceError and CostError Columns to Your DataFrame

Hey there! Let's get this DataFrame sorted out with the error columns you need. Here's a straightforward way to implement the logic you described using pandas:

Step 1: Set Up Your DataFrame

First, let's recreate your initial data to work with:

import pandas as pd

# Initialize the original DataFrame
df = pd.DataFrame({
    'Price1': [1, 2],
    'Price2': [1, 4],
    'Cost1': [3, 3],
    'Cost2': [6, 3],
    '%Price': [0, 100],
    '%Cost': [100, 0]
})

Step 2: Generate Error Columns

We'll use apply() to check each row against your 50% threshold and build the error strings only when the condition is met.

Note: I noticed a potential typo in your CostError example (you wrote "Cost1 is 3 and Cost1 is 6" instead of referencing Cost2). I've adjusted the code to use Cost1 and Cost2 since that makes logical sense with your data—if you did intend to repeat Cost1, just swap row['Cost2'] for row['Cost1'] in the CostError line.

# Create PriceError column
df['PriceError'] = df.apply(
    lambda row: f"Price1 is {row['Price1']} and Price2 is {row['Price2']}. The %Price is {row['%Price']}."
    if row['%Price'] >= 50
    else '',
    axis=1
)

# Create CostError column
df['CostError'] = df.apply(
    lambda row: f"Cost1 is {row['Cost1']} and Cost2 is {row['Cost2']}. The %Cost is {row['%Cost']}."
    if row['%Cost'] >= 50
    else '',
    axis=1
)

Step 3: View the Result

After running the code, your DataFrame will look like this:

Price1Price2Cost1Cost2%Price%CostPriceErrorCostError
11360100Cost1 is 3 and Cost2 is 6. The %Cost is 100.
24331000Price1 is 2 and Price2 is 4. The %Price is 100.

Quick Explanation:

  • apply(axis=1) lets us run a function on each row of the DataFrame
  • The ternary operator (if/else) checks if the percentage meets or exceeds 50%
  • F-strings make it easy to plug in the row's values directly into the error message
  • Rows that don't meet the threshold get an empty string (replace '' with pd.NA if you prefer missing values instead)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:44:31