如何对数据框使用“应用”并避免SettingWithCopyWarning?

时间:2018-10-12 13:08:00

标签: python pandas dataframe apply

我在DataFrame上使用以下功能:

df['error_code'] = df.apply(lambda row: replace_semi_colon(row), axis=1)

嵌入式功能是:

def replace_semi_colon(row):
    errrcd = str(row['error_code'])  
    semi_colon_pat = re.compile(r'.*;.*')

    if pd.notnull(errrcd):

      if semi_colon_pat.match(errrcd):
        mod_error_code = str(errrcd.replace(';',':'))
        return  mod_error_code

    return errrcd

但是我收到了(著名的)

  

SettingWithCopyWarning

我读了很多帖子,但仍然不知道如何预防。

奇怪的是,我以相同的方式使用其他apply函数,但它们不会引发相同的错误。

有人可以解释为什么我收到此警告吗?

1 个答案:

答案 0 :(得分:0)

apply之前还有另一条声明:

df = df.query('error_code != "BM" and eror_code != "PM"')

我将其修改为:

df.loc[:] = df.query('error_code != "BM" and eror_code != "PM"')

解决了。