如何基于条件为Pandas DataFrame列赋值:设备类别推荐问题
Alright, let's break down how to solve this problem. You've got device data with scores across three categories (A/B/C) and their current class, and you need to figure out if each device should switch to the category where it has the highest score. Here are two practical implementations:
1. Python Implementation (Using Pandas)
Pandas is perfect for tabular data tasks like this—it lets you automate the process efficiently, especially if you have a large dataset.
Step-by-Step Code
import pandas as pd # Define your input data device_data = { 'device_id': [1, 2], 'A': [70, 45], 'B': [35, 90], 'C': [40, 34], 'Current Class': ['C', 'B'] } # Convert to a pandas DataFrame df = pd.DataFrame(device_data) # Find the category with the highest score for each device df['Recommended Class'] = df[['A', 'B', 'C']].idxmax(axis=1) # Determine if a class change is needed df['Class Change Recommended'] = df.apply( lambda row: 'Yes' if row['Recommended Class'] != row['Current Class'] else 'No', axis=1 ) # Reorder columns to match your expected output final_output = df[['device_id', 'A', 'B', 'C', 'Current Class', 'Class Change Recommended', 'Recommended Class']] # Print or export the result print(final_output)
Output
| device_id | A | B | C | Current Class | Class Change Recommended | Recommended Class |
|---|---|---|---|---|---|---|
| 1 | 70 | 35 | 40 | C | Yes | A |
| 2 | 45 | 90 | 34 | B | No | B |
2. Excel Implementation
If you prefer working with spreadsheets, here's how to do it manually:
Step 1: Calculate Recommended Class
In an empty column (say, column F), enter this formula in cell F2 and drag it down:=INDEX($B$1:$D$1, MATCH(MAX(B2:D2), B2:D2, 0))
This finds the category label (A/B/C) corresponding to the highest score in the row's A/B/C columns.Step 2: Check for Class Change
In another empty column (column G), enter this formula in cell G2 and drag down:=IF(F2=E2, "No", "Yes")
This compares the recommended class to the current class and returns "Yes" if they differ, "No" otherwise.Step 3: Rearrange Columns
Just drag the columns into the order you need (device_id, A, B, C, Current Class, Class Change Recommended, Recommended Class) to match your expected output.
内容的提问来源于stack exchange,提问作者Shuvayan Das

