如何用Pandas与Numpy获取置信度最高的类别及对应置信值?
Hey there! Sounds like you're almost there—you've got the max confidence values locked in, just missing the link to their matching categories. Let's fix that quickly, assuming you're working with a pandas DataFrame (since you used data.max(axis=1)):
Step 1: Target your confidence columns explicitly
First, define the 3 columns that hold your confidence data. Let's say their names are Cat_X, Cat_Y, Cat_Z—swap these out for your actual column names to avoid accidentally including other columns like TC_Name or Failure.
Step 2: Fetch the category tied to each row's max confidence
Use pandas' idxmax(axis=1) method—it returns the column name (your category label) where the maximum value occurs in each row. Pair this with your existing max value call:
# Define your confidence columns confidence_cols = ['Cat_X', 'Cat_Y', 'Cat_Z'] # Add max confidence value to your DataFrame df['MaxConfidence'] = df[confidence_cols].max(axis=1) # Add the category name linked to that max value df['MaxErrCategory'] = df[confidence_cols].idxmax(axis=1)
Step 3: Build your final dataset
Now just select the 4 columns you need and make a copy to avoid any unintended reference issues:
new_dataset = df[['TC_Name', 'Failure', 'MaxErrCategory', 'MaxConfidence']].copy()
Quick note on tie scenarios
If multiple categories have the same max confidence in a row, idxmax will return the first one it encounters (left-to-right in your column order). If you need to capture all matching categories for ties, use a custom apply function like this:
def get_all_max_categories(row): max_val = row[confidence_cols].max() return ', '.join([col for col in confidence_cols if row[col] == max_val]) df['MaxErrCategory'] = df.apply(get_all_max_categories, axis=1)
That should give you exactly the dataset you're aiming for!
内容的提问来源于stack exchange,提问作者Ashutosh Srivastava

