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

Pandas循环中.loc位置切片警告的替代方案咨询

解决DataFrame.loc切片触发的FutureWarning问题

问题背景

通过for循环迭代DataFrame行时,执行以下代码重置当前行及之前所有行的atr_Lts列值:

cummax.loc[:i, 'atr_Lts'] = cummax.loc[cummax.index[i], 'atr_Lts']

代码可正常运行,但触发FutureWarning:

Slicing a positional slice with .loc is not supported, and will raise TypeError in a future version. Use .loc with labels or .iloc with positions instead.

需要替换为合规的实现方式。

示例数据

DataFrame示例:

Date          Close       atr     atr_Lts     atr_Sts       atrts
2022-02-23  421.950012       NaN  371.614245  413.538855  413.538855
2022-02-24  428.299988       NaN  371.614245  413.538855  413.538855
2022-02-25  437.750000       NaN  371.614245  413.538855  413.538855
2022-02-28  436.630005       NaN  371.614245  413.538855  413.538855
2022-03-01  429.980011       NaN  371.614245  413.538855  413.538855

cummax.info()输出:

Data columns (total 5 columns):
 #   Column   Non-Null Count  Dtype
---  ------   --------------  -----
 0   Close    125 non-null    float64
 1   atr      112 non-null    float64
 2   atr_Lts  125 non-null    float64
 3   atr_Sts  112 non-null    float64
 4   atrts    112 non-null    float64
dtypes: float64(5)

合规替代方案

方案1:用.iloc处理位置索引

.loc仅支持标签切片,位置切片需用.iloc实现。结合列位置索引定位目标列:

for i in range(len(cummax)):
    current_val = cummax.iloc[i]['atr_Lts']
    # 获取atr_Lts列的位置索引
    col_pos = cummax.columns.get_loc('atr_Lts')
    # 用.iloc切片行范围,定位列位置赋值
    cummax.iloc[:i+1, col_pos] = current_val

注:.iloc[:i+1]对应原代码.loc[:i]的行范围(包含第i行),逻辑完全一致。

方案2:用.loc结合行标签切片

若DataFrame索引为唯一标签(如示例中的日期索引),直接遍历索引标签进行切片:

for idx in cummax.index:
    current_val = cummax.loc[idx, 'atr_Lts']
    cummax.loc[:idx, 'atr_Lts'] = current_val

此写法完全符合.loc的设计规范,不会触发警告。

方案3:矢量化操作替代循环(推荐)

循环处理DataFrame效率较低,若需求是将atr_Lts列所有值统一为最后一行的值,直接用矢量化赋值即可:

cummax['atr_Lts'] = cummax['atr_Lts'].iloc[-1]

若atr_Lts是动态逐行更新后再覆盖前面行,优先选用前两种方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 14:45:37