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

如何解决SettingWithCopyWarning警告?Pandas函数代码问题咨询

解决Pandas的SettingWithCopyWarning问题

问题重现

编写了以下Pandas函数:

def get_unique_df(df: pd.DataFrame) -> pd.DataFrame:
    unique_df = df.drop_duplicates(subset=['Value', 'Label'], keep='first')
    unique_df.index = range(len(unique_df.index))
    unique_df['Label'] = unique_df['Label'].astype(int)
    return unique_df

运行时触发警告:

SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

问题原因

drop_duplicates返回的对象可能是原DataFrame的视图而非独立副本,直接通过unique_df['Label']赋值时,Pandas无法确定你是要修改原DataFrame还是副本,因此抛出警告。

解决方案

提供三种有效修改方式:

1. 强制生成副本

在drop_duplicates后调用.copy(),确保unique_df是独立的DataFrame:

def get_unique_df(df: pd.DataFrame) -> pd.DataFrame:
    unique_df = df.drop_duplicates(subset=['Value', 'Label'], keep='first').copy()
    unique_df.index = range(len(unique_df.index))
    unique_df['Label'] = unique_df['Label'].astype(int)
    return unique_df

2. 使用.loc明确索引赋值

通过.loc[:, 'Label']指定完整的行和列索引,符合Pandas的安全赋值规范:

def get_unique_df(df: pd.DataFrame) -> pd.DataFrame:
    unique_df = df.drop_duplicates(subset=['Value', 'Label'], keep='first')
    unique_df.index = range(len(unique_df.index))
    unique_df.loc[:, 'Label'] = unique_df['Label'].astype(int)
    return unique_df

3. 链式操作简化代码

用reset_index替代手动重置索引,结合assign方法安全修改列类型,代码更简洁:

def get_unique_df(df: pd.DataFrame) -> pd.DataFrame:
    return df.drop_duplicates(subset=['Value', 'Label'], keep='first')\
             .reset_index(drop=True)\
             .assign(Label=lambda x: x['Label'].astype(int))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 13:27:17