如何在SAS中将"X months"格式的字符变量转换为数值变量?
Hey there! Don't sweat it—this is a totally common data cleaning task, and with 1.7 million rows, we want something efficient that won't bog down your workflow. Below are straightforward solutions for the two most common tools used for this kind of work: R and Python (Pandas).
R Solutions
Using stringr (tidyverse friendly)
The str_extract function makes it easy to pull out the numeric part directly:
library(stringr) # Replace df and month_col with your actual dataset/column names df$numeric_months <- as.numeric(str_extract(df$month_col, "\\d+"))
The \\d+ regex pattern matches one or more digits—perfect for grabbing the number before " months".
Base R (no extra packages needed)
If you prefer sticking to base R, gsub works great by removing all non-numeric characters:
df$numeric_months <- as.numeric(gsub("\\D", "", df$month_col))
\\D matches any character that's not a digit, so replacing those with nothing leaves you with just the number, which we then convert to numeric.
Python (Pandas) Solutions
Using str.extract
Pandas' string methods are optimized for large datasets, so this will handle 1.7M rows smoothly:
import pandas as pd # Replace df and month_col with your actual dataset/column names df['numeric_months'] = df['month_col'].str.extract(r'(\d+)', expand=False).astype(int)
The (\d+) captures the numeric group, extract pulls it out, and astype(int) converts it to an integer type (use float if you have decimal values, though your question mentions whole months).
Using str.replace
Another quick option is to strip out all non-numeric characters first:
df['numeric_months'] = df['month_col'].str.replace(r'\D', '', regex=True).astype(int)
This replaces any non-digit character with an empty string, leaving just the numeric value to convert.
Quick Note on Edge Cases
Keep an eye out for rows that don't follow the "X months" format—these will turn into NA (R) or NaN (Pandas). You can check for these with:
- R:
df[is.na(df$numeric_months), ] - Pandas:
df[df['numeric_months'].isna()]
That should get you sorted! 😊
内容的提问来源于stack exchange,提问作者TheSaint321

