简体   繁体   English

熊猫-另一种SettingWithCopyWarning:我正在使用.loc替换特定值,但仍收到警告

[英]pandas - another SettingWithCopyWarning: I am using .loc to replace specific values, but still get the warning

I thought I followed the best practice: 我以为我遵循了最佳实践:

import pandas as pd
df=pd.DataFrame({'cond':['a', 'b', 'a'], 'value':[1.5, 2.5, 3.5]})

mask = df.cond == 'a'
df.loc[mask, 'value'] = df.loc[mask, 'value'] * (-1)

In essence, is condition is met, replace a value with it's negative. 本质上,条件满足时,用它的负数代替一个值。 What is the better way to perform this operation so I do not trigger the warning? 什么是执行此操作以便不触发警告的更好方法?

The problem turns out not to be with the code as shown. 问题出在与所示代码无关。 That code example worked fine. 该代码示例运行良好。

In the real world, df is a created as follows: df = df2[['cond', 'value']] . 在现实世界中, df是如下创建的: df = df2[['cond', 'value']] adding .copy() to this line, fixed the warning. .copy()添加到此行中,修复了警告。

This solution was pointed our by @jezrael in the comments. @jezrael在评论中指出了该解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM