如何规范使用pd.to_datetime将object转为datetime并消除警告?
解决方案
1. 修复日期类型转换问题
你用dt.strftime('%Y-%m')会把datetime对象转换成字符串,所以数据类型始终是object。要保留datetime64[ns]类型,只需要完成datetime转换即可,不需要额外格式化字符串:
# 直接转换为datetime原生类型 cleaned_df['month'] = pd.to_datetime(cleaned_df['month'])
如果需要显示成YYYY-MM格式,不用修改数据类型,只需设置pandas的显示选项:
pd.options.display.date_format = '%Y-%m'
这样数据类型依然是datetime,但显示出来就是你要的格式。
2. 消除SettingWithCopyWarning警告
这个警告是因为cleaned_df大概率是从其他DataFrame切片得到的副本,而非独立的DataFrame。两种常用解决方法:
- 方法一:创建时显式复制
如果cleaned_df是通过切片生成的(比如cleaned_df = original_df[cols]),改成:
cleaned_df = original_df[cols].copy()
- 方法二:用.loc定位赋值
通过.loc明确指定行列进行赋值,避免直接修改副本:
cleaned_df.loc[:, 'month'] = pd.to_datetime(cleaned_df['month'])
结合重命名的完整最佳实践代码
注意你已经把month重命名为yyyy_mm,后续操作要使用新列名:
# 1. 确保cleaned_df是独立副本(如果是切片生成的) cleaned_df = cleaned_df.copy() # 2. 重命名列 cleaned_df.rename(columns={ 'month':'yyyy_mm', 'no_of_rainy_days':'no_of_rainy_days (days)', 'total_rainfall':'total_rainfall (mm)', 'mean_rh':'monthly_mean_humidity (%)', 'mean_sunshine_hrs':'mean_sunshine_hrs (hr)', 'cpi':'consumer_price_index (%)' }, inplace=True) # 3. 转换日期列类型 cleaned_df.loc[:, 'yyyy_mm'] = pd.to_datetime(cleaned_df['yyyy_mm']) # 可选:设置日期显示格式 pd.options.display.date_format = '%Y-%m'
内容的提问来源于stack exchange,提问作者ricenix
相关产品推荐
相关产品推荐

