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

UCI乳腺癌数据集字符串列有序数值编码问题咨询

Fixing Ordered Numeric Encoding for Your Breast Cancer Dataset

Hey there, I see the issue you're facing—using pd.Categorical().codes directly doesn't give you the sorted order you want for your encoding. That's because by default, pandas sets the category order based on the first occurrence of values in the data, not alphabetical/sorted order. Let's fix this with a straightforward approach that ensures your categories are sorted before encoding.

Step-by-Step Solution

The key is to explicitly define the sorted category list for each column before converting to a categorical type. Here's how to do it for all your string columns:

  1. Define a helper function that takes a column, sorts its unique values, converts it to an ordered categorical, and returns the numeric codes.
  2. Apply this function to all your target columns in one go.

Full Code Example

import pandas as pd

# Assuming your DataFrame is named 'df' and headerList is your column list
list_of_columns = df.columns  # Or use your existing headerList variable

def sorted_categorical_encode(column):
    # Get sorted list of unique values from the column
    sorted_categories = sorted(column.unique())
    # Convert column to ordered categorical with sorted categories
    ordered_cat = pd.Categorical(column, categories=sorted_categories, ordered=True)
    # Return the numeric codes
    return ordered_cat.codes

# Apply the encoding to all specified columns
df[list_of_columns] = df[list_of_columns].apply(sorted_categorical_encode)

Why This Works

  • For columns like Class, sorting the unique values gives ['no-recurrence-events', 'recurrence-events'], so the code will map the first to 0 and the second to 1—exactly what you want.
  • For age, sorted unique values will be ['20-29', '30-39', '40-49', ...], resulting in the ordered numeric mapping you specified.
  • By setting ordered=True, we ensure the categorical type recognizes the hierarchy, which also helps if you need to perform any ordered operations later (like comparisons).

Verify the Result

You can double-check any column to confirm the encoding matches your expectations:

# Check Class column mappings
print(pd.Categorical(df['Class']).categories)
print(df['Class'].value_counts())

This should give you the sorted, ordered numeric encoding you're looking for!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 16:42:34