如何将Pandas DataFrame中A-Z类别的字符列转换为整数?
Here are a few straightforward methods to turn your uppercase letter-based 'class' column into integers, depending on whether you want alphabetical ordering or just unique integer identifiers:
Method 1: Map to Alphabetical Position (0 or 1-indexed)
This method directly converts each letter to its position in the alphabet (e.g., 'A' → 0, 'B' →1, ..., 'Z'→25, or start at 1 if you prefer).
import pandas as pd # Sample DataFrame based on your example data = { 'x1': [180.9863129, 52.20132828, -17.17127419, 37.28710938, -132.2395782, -12.52811623], 'x2': [-0.266379416, 28.93587875, 29.97013283, -69.96691132, 27.02541733, -87.90951538], 'km': [24,16,17,3,15,22], 'gmm': [19,14,16,6,18,5], 'class': ['T','I','D','N','G','S'] } df = pd.DataFrame(data) # Convert to 0-indexed alphabetical integers df['class'] = df['class'].apply(lambda x: ord(x) - ord('A')) # Or convert to 1-indexed (A=1, B=2, ... Z=26) # df['class'] = df['class'].apply(lambda x: ord(x) - ord('A') + 1)
After running this, your 'class' column will have values like: 'T' →19, 'I'→8, 'D'→3, etc. (for 0-indexed).
Method 2: Use pd.factorize() for Unique Identifiers (Order of Appearance)
If alphabetical order doesn't matter and you just want a unique integer for each distinct letter (based on their first occurrence in the DataFrame), use factorize():
df['class'] = pd.factorize(df['class'])[0]
In your example, this would assign:
- 'T' →0, 'I'→1, 'D'→2, 'N'→3, 'G'→4, 'S'→5
Method 3: Custom Mapping Dictionary
You can also create an explicit dictionary to map each letter to an integer, which gives you full control over the mapping:
# Create a dictionary for A-Z to 0-25 letter_map = {chr(ord('A') + idx): idx for idx in range(26)} # Apply the mapping df['class'] = df['class'].map(letter_map)
This works the same as Method 1 but uses a pre-defined map instead of a lambda function. It's handy if you need to adjust the mapping later (e.g., assign specific integers to certain letters).
Quick Notes:
- If your 'class' column has lowercase letters, add
.upper()to the lambda or mapping to ensure consistency:lambda x: ord(x.upper()) - ord('A') - All methods assume your 'class' values are only A-Z; if there are other characters, you might want to add error handling (like
try-exceptblocks) to avoid issues.
内容的提问来源于stack exchange,提问作者Jadu Sen

