如何消除从数组设置DataFrame整列时的原地FutureWarning?
解决pandas 1.5.0中iloc赋值的FutureWarning问题
在pandas 1.5.0中,使用iloc给不同dtype的数组赋值时会触发FutureWarning,提示未来版本将改为原地修改语义。如果仅需消除警告、不关心是否原地操作,可参考以下几种方案:
可行解决方案
1. 替换为官方推荐的赋值写法
这是最稳妥的方案,既消除警告,又符合pandas未来版本的语义规范:
- 当列名唯一时,直接通过列名赋值:
df = pd.DataFrame({'price': [11.1, 12.2]}, index=['book1', 'book2']) original_prices = df['price'] new_prices = np.array([98, 99]) df['price'] = new_prices # 替换df.iloc[:, 0] = new_prices - 当列名不唯一时,使用
isetitem方法按位置赋值:df.isetitem(0, new_prices)
2. 显式匹配新值与原列的dtype
如果希望保留iloc的写法,可以将新值的dtype转换为和目标列一致,这样不会触发警告(此时会直接原地修改):
df = pd.DataFrame({'price': [11.1, 12.2]}, index=['book1', 'book2']) new_prices = np.array([98, 99], dtype=df['price'].dtype) # 匹配原列dtype df.iloc[:, 0] = new_prices
3. 针对性屏蔽该FutureWarning
如果只是临时需要消除警告,且不想修改代码逻辑,可以用warnings模块精准屏蔽该类警告(不建议全局屏蔽所有警告,避免遗漏其他重要提示):
import warnings import pandas as pd import numpy as np df = pd.DataFrame({'price': [11.1, 12.2]}, index=['book1', 'book2']) new_prices = np.array([98, 99]) with warnings.catch_warnings(): warnings.filterwarnings( "ignore", category=FutureWarning, message="In a future version, df.iloc[:, i] = newvals will attempt to set the values inplace" ) df.iloc[:, 0] = new_prices
方案优先级
优先选择方案1,因为它完全符合pandas的迭代方向,不会在未来版本中出现兼容性问题;其次是方案2,适合需要保留位置赋值逻辑的场景;方案3作为临时应急手段,尽量少用。
内容的提问来源于stack exchange,提问作者lumbric
相关产品推荐
相关产品推荐

