pandas standalone series and from dataframe different behavior
<p>Here is my code and warning message. If I change <code>s</code> to be a standalone <code>Series</code> by using <code>s = pd.Series(np.random.randn(5))</code>, there will no such errors. Using Python 2.7 on Windows.</p>

<p>It seems Series created from standalone and Series created from a column of a data frame are different behavior? Thanks.</p>

<p>My purpose is to change the Series value itself, other than change on a copy.</p>

<p><strong>Source code</strong>,</p>

<pre><code>import pandas as pd

sample = pd.read_csv('123.csv', header=None, skiprows=1,
       dtype={0:str, 1:str, 2:str, 3:float})
sample.columns = pd.Index(data=['c_a', 'c_b', 'c_c', 'c_d'])
sample['c_d'] = sample['c_d'].astype('int64')
s = sample['c_d']
#s = pd.Series(np.random.randn(5))
for i in range(len(s)):
    if s.iloc[i] &gt; 0:
        s.iloc[i] = s.iloc[i] + 1
    else:
        s.iloc[i] = s.iloc[i] - 1
</code></pre>

<p><strong>Warning message</strong>,</p>

<pre><code>C:\Python27\lib\site-packages\pandas\core\indexing.py:132: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self._setitem_with_indexer(indexer, value)
</code></pre>

<p><strong>Content of 123.csv</strong>,</p>

<pre><code>c_a,c_b,c_c,c_d
hello,python,numpy,0.0
hi,python,pandas,1.0
ho,c++,vector,0.0
ho,c++,std,1.0
go,c++,std,0.0
</code></pre>

<p><strong>Edit 1</strong>, seems lambda solution does not work, tried to print <code>s</code> before and after, the same value,</p>

<pre><code>import pandas as pd

sample = pd.read_csv('123.csv', header=None, skiprows=1,
       dtype={0:str, 1:str, 2:str, 3:float})
sample.columns = pd.Index(data=['c_a', 'c_b', 'c_c', 'c_d'])
sample['c_d'] = sample['c_d'].astype('int64')
s = sample['c_d']
print s
s.apply(lambda x:x+1 if x&gt;0 else x-1)
print s

0    0
1    1
2    0
3    1
4    0
Name: c_d, dtype: int64
Backend TkAgg is interactive backend. Turning interactive mode on.
0    0
1    1
2    0
3    1
4    0
</code></pre>

<p>regards,
Lin</p>

<p>By doing <code>s = sample['c_d']</code>, if you make a change to the value of <code>s</code> then your original Dataframe <code>sample</code> also changes. That's why you got the warning.</p>

<p>You can do <code>s = sample[c_d].copy()</code> instead, so that changing the value of <code>s</code> doesn't change the value of <code>c_d</code> column of the Dataframe <code>sample</code>.</p>

python python-2.7 pandas numpy dataframe