You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用pd.to_datetime等方法将月份列整数转为两位格式?及map函数替换后NaN值的原因分析

Fixing Month Format Conversion & Resolving NaN Issues in Pandas

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:

  1. Match the dictionary key type to your column type
    Update the dictionary to use integer keys instead of strings, and add fillna() 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))
    
  2. Convert the column to strings first
    Turn your integer month values into strings before mapping, then use fillna() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 15:32:48