如何用Pandas新增PriceError和CostError列(基于指定列与阈值)
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:
| Price1 | Price2 | Cost1 | Cost2 | %Price | %Cost | PriceError | CostError |
|---|---|---|---|---|---|---|---|
| 1 | 1 | 3 | 6 | 0 | 100 | Cost1 is 3 and Cost2 is 6. The %Cost is 100. | |
| 2 | 4 | 3 | 3 | 100 | 0 | Price1 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
''withpd.NAif you prefer missing values instead)
内容的提问来源于stack exchange,提问作者user8685751

