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

为何Pandas抛出“设置不兼容dtype”FutureWarning?

问题原因分析

你触发警告的核心原因是:df1.apply(rush_hourizer, axis=1)返回的Series dtype是int64,而目标列rush_hour的 dtype 是int32,两者精度不匹配。

虽然你返回的是Python原生int,但pandas会自动将这些值包装为int64类型的Series(Python int是任意精度,pandas默认用int64兼容),和目标列的int32存在 dtype 冲突,因此触发FutureWarning。

解决方案

方案1:显式转换 dtype 后赋值

直接将apply的结果转换为int32,再赋值给目标列:

mask = (df1.day != 'saturday') & (df1.day != 'sunday')
df1.loc[mask, 'rush_hour'] = df1.apply(rush_hourizer, axis=1).astype('int32')

方案2:用矢量化操作替代apply(更高效)

apply是逐行遍历,效率较低,推荐用pandas矢量化逻辑实现相同功能,同时直接控制 dtype:

mask = (df1.day != 'saturday') & (df1.day != 'sunday')
# 定义高峰时段条件
is_rush = ((df1['rush_hour'] >= 6) & (df1['rush_hour'] < 10)) | \
          ((df1['rush_hour'] >= 16) & (df1['rush_hour'] < 20))
# 转换为int32后赋值
df1.loc[mask, 'rush_hour'] = is_rush.astype('int32')

额外优化:简化自定义函数(如果坚持用apply)

你的函数可以简化为接收单个小时值,而非整行Series,减少不必要的索引操作:

def rush_hourizer(hour):
    return 1 if (6 <= hour < 10) or (16 <= hour < 20) else 0

# 直接对rush_hour列apply,而非整行
mask = (df1.day != 'saturday') & (df1.day != 'sunday')
df1.loc[mask, 'rush_hour'] = df1.loc[mask, 'rush_hour'].apply(rush_hourizer).astype('int32')

内容的提问来源于stack exchange,提问作者ssou

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 12:56:04