Modifying a pandas dataframe that may be a view
<p>I have a pandas <code>DataFrame</code> <code>df</code> that is returned from a function and I generally don't know whether it is an independent object or a view on another <code>DataFrame</code>. I want to add new columns to it but don't want to copy it unnecessarily.</p>

<pre><code>df['new_column'] = 0
</code></pre>

<p>may give a nasty warning about modifying a copy</p>

<pre><code>df = df.copy()
</code></pre>

<p>may be expensive if df is large.
What's the best way here?</p>

<p>you should use an indexer to create your s1 such has:</p>

<pre><code>import pandas as pd
s = pd.DataFrame({'a':[1,2], 'b':[2,3]})
indexer = s[s.a &gt; 1].index
s1 = s.loc[indexer, :]
s1['c'] = 0
</code></pre>

<p>should remove the warning.</p>

python pandas