如何用pd.to_datetime等方法将月份列整数转为两位格式?及map函数替换后NaN值的原因分析
First, let's tackle the NaN problem you're seeing with your map() approach. The root cause here is a type mismatch: your month column stores integers (1, 2, ..., 9) but your vals_to_replace dictionary uses string keys ('1', '2', ..., '9'). When pandas tries to map an integer 1 to the string key '1', it can't find a match, so it returns NaN instead.
Fixing the Original map() Method
You have two easy ways to fix this:
Match the dictionary key type to your column type
Update the dictionary to use integer keys instead of strings, and addfillna()to preserve values like 10, 11, 12 that don't need padding:vals_to_replace = {1:'01', 2:'02', 3:'03', 4:'04', 5:'05', 6:'06', 7:'07', 8:'08', 9:'09'} data['month'] = data['month'].map(vals_to_replace).fillna(data['month'].astype(str))Convert the column to strings first
Turn your integer month values into strings before mapping, then usefillna()to keep unmodified values:vals_to_replace = {'1':'01','2':'02','3':'03','4':'04','5':'05','6':'06','7':'07','8':'08','9':'09'} data['month'] = data['month'].astype(str).map(vals_to_replace).fillna(data['month'].astype(str))
Using pd.to_datetime for Conversion
This method is more robust and handles all month values (1-12) automatically, no need for manual dictionaries:
# Convert integer month to datetime, then extract 2-digit month string data['month'] = pd.to_datetime(data['month'], format='%m').dt.strftime('%m')
Here's how it works:
format='%m'tells pandas your input is a numeric month value (1-12)dt.strftime('%m')formats the datetime object into a 2-digit string (e.g., 1 → '01', 12 → '12')
Even Simpler: Use str.zfill()
If you don't need to use datetime functions, converting to strings and using zfill(2) is the most concise solution—it pads any single-digit string with a leading zero:
data['month'] = data['month'].astype(str).str.zfill(2)
内容的提问来源于stack exchange,提问作者Arindam Ghosh

