Python中如何将数据列从Object类型统一转换为int64类型?
Got it, let's work through converting your mixed Object type Result column to int64 step by step. Your data has a mix of values—some with units (like "98.8 PG/ML H"), pure decimal strings, and non-numeric entries like "CREDIT"—so we need to clean the data first before changing the type.
Step 1: Extract numeric values from messy strings
First, we'll use regular expressions to pull out the numeric part from each entry. This handles cases where units are attached to numbers. We'll write a helper function for this:
import pandas as pd import re def extract_num(val): # Match integers or decimals (supports positive/negative values too) num_match = re.search(r'[-+]?\d*\.\d+|\d+', str(val)) if num_match: # Convert the matched string to float first (since we have decimals) return float(num_match.group()) else: # Return NaN for entries with no numeric data (like "CREDIT") return pd.NA # Apply the function to your Result column data['Result'] = data['Result'].apply(extract_num)
Step 2: Handle non-numeric entries
After extracting, you'll have NaN values where there was no number (like the "CREDIT" entry). You need to decide how to handle these based on your use case:
- Replace with
0(common if missing/non-numeric means 0):data['Result'] = data['Result'].fillna(0) - Or keep
NaNand convert toInt64(capital I, which supports nullable integers) instead ofint64if you want to preserve missing values:data['Result'] = data['Result'].astype('Int64')
Step 3: Convert to int64
If you've filled NaN with a numeric value (like 0), you can now convert to int64. Note that we first converted to float to handle decimals—direct conversion from string to int would fail for decimal values:
# Optional: Round decimals if you want the nearest integer instead of truncating data['Result'] = data['Result'].round() # Convert to int64 data['Result'] = data['Result'].astype('int64')
Testing with your sample data
Let's see what happens to your example entries:
- "98.8 PG/ML H" → 98.8 → rounded to 99 (or truncated to 98 if you skip rounding) → int64
- "8.20000" → 8.2 → 8 or 9 → int64
- "26.8 PG/ML H" →26.8 →27 or 26 → int64
- "40.8 PG/ML H" →40.8 →41 or 40 → int64
- "CREDIT" → NaN → 0 (if you filled) → int64
- "15.30000" →15.3 →15 or 16 → int64
That should get your column into a clean int64 format!
内容的提问来源于stack exchange,提问作者medlearning

