求助:将atp_main中object类型年龄列转为整数类型的方法
Hey there! Let's fix that age conversion issue with your atp_main DataFrame. The problem here is that your winner_age and loser_age columns are stored as object type (likely string-formatted floats), which is why you can't directly convert them to integers. Let's break this down into simple, actionable steps:
Step 1: Convert Object Columns to Numeric Values
First, we need to turn those string-based floats into actual numeric values. We'll use pd.to_numeric to handle this, and also catch any invalid entries (like non-numeric strings) by converting them to NaN (we can clean those up next).
import pandas as pd # Convert winner_age to numeric, coercing invalid entries to NaN df['winner_age'] = pd.to_numeric(df['winner_age'], errors='coerce') # Repeat the process for loser_age df['loser_age'] = pd.to_numeric(df['loser_age'], errors='coerce')
Step 2: Handle Missing Values (If Needed)
If the conversion created NaN values (from invalid entries), you'll need to decide how to handle them. Here are two common, practical options:
- Drop rows with missing ages: Use this if missing ages aren't critical for your analysis.
df = df.dropna(subset=['winner_age', 'loser_age']) - Fill missing values: Use a reasonable default like the average age of the dataset:
avg_winner_age = df['winner_age'].mean() df['winner_age'] = df['winner_age'].fillna(avg_winner_age) avg_loser_age = df['loser_age'].mean() df['loser_age'] = df['loser_age'].fillna(avg_loser_age)
Step 3: Convert to Integers
Now that we have proper numeric columns, we can convert them to integers. Choose the method that fits your needs:
Option 1: Truncate Decimal Places (e.g., 22.999 → 22)
This simply cuts off the decimal part without rounding, matching the examples you shared:
df['winner_age'] = df['winner_age'].astype(int) df['loser_age'] = df['loser_age'].astype(int)
Option 2: Round to Nearest Integer (e.g., 22.6 → 23)
If you prefer to round to the closest whole number instead:
df['winner_age'] = df['winner_age'].round().astype(int) df['loser_age'] = df['loser_age'].round().astype(int)
Why Directly Converting to Int Failed
The original columns were stored as object/string type—Python can't convert a string like "22.321234" directly to an integer. You first need to parse it into a float (or numeric type), then convert that float to an integer. That's why your initial direct conversion attempt didn't work!
内容的提问来源于stack exchange,提问作者Mazz

