UCI乳腺癌数据集字符串列有序数值编码问题咨询
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:
- Define a helper function that takes a column, sorts its unique values, converts it to an ordered categorical, and returns the numeric codes.
- 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

