SettingWithCopyWarning on Column Creation
<p>I'm trying to create a moving average column for my data called 'mv_avg'. I'm getting a SettingWithCopyWarning that I have been unable to fix. I could suppress the warning, but I cannot figure out where in my code I am creating a copy, and I want to utilize best practices. I've created a generalizable example below to illustrate the problem.</p>

<pre><code>data = {'category' : ['a', 'a', 'a', 'b', 'b', 'b'], 'value' : [1,2,3,4,5,6]}
df = pd.DataFrame(data)
df_a = df.loc[df['category'] == 'a']
df_a['mv_avg'] = df_a['value'].rolling(window=2).mean()
</code></pre>

<p>This returns: </p>

<pre><code>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
</code></pre>

<p>I've also tried the more verbose version:</p>

<pre><code>df_a.loc[: , 'mv_avg'] = df_a.loc[:,'value'].rolling(window=2).mean()
</code></pre>

<p>but I get the same error. What is the best way to accomplish this without the warning?</p>

<p>you can create a copy using .copy()</p>

<pre><code>import pandas as pd
data = {'category' : ['a', 'a', 'a', 'b', 'b', 'b'], 'value' : [1,2,3,4,5,6]}
df = pd.DataFrame(data)
df_a = df.loc[df['category'] == 'a'].copy()
df_a['mv_avg'] = df_a['value'].rolling(window=2).mean()
</code></pre>

<p>or you can use an indexer  such has :</p>

<pre><code>import pandas as pd
data = {'category' : ['a', 'a', 'a', 'b', 'b', 'b'], 'value' : [1,2,3,4,5,6]}
df = pd.DataFrame(data)
indexer = df[df['category'] == 'a'].index
df_a = df.loc[indexer, :]
df_a['mv_avg'] = df_a['value'].rolling(window=2).mean()
</code></pre>

python pandas