Editing a value in a DataFrame
<p>I'm trying to:</p>

<p>Import a CSV of UPC codes into a dataframe. If the UPC code is 11 characters , append '0' to it. Ex: 19962123818  --> 019962123818</p>

<p>This is the code:</p>

<pre><code> #check UPC code length. If 11 characters, adds '0' before. If &lt; 11 or &gt; 13, throws Error
for index, row in clean_data.iterrows():
    if len(row['UPC']) == 11:
        row['UPC'] = ('0' + row['UPC'])
        #clean_data.set_value(row, 'UPC',('0' + (row['UPC']))
        print ("Edited UPC:", row['UPC'], type(row['UPC']))
    if len(row['UPC']) &lt; 11 or len(row['UPC']) &gt; 13:
        print ('Error, UPC length &lt; 11 or &gt; 13:')
        print ("Error in UPC:", row['UPC'])
        quit()
</code></pre>

<p>However, when I print the data, the original value is not edited:</p>

<p><a href="https://i.stack.imgur.com/xMad7.png" rel="nofollow"><img src="https://i.stack.imgur.com/xMad7.png" alt="enter image description here"></a></p>

<p>Does anyone know what is causing this issue?</p>

<p>I tried the set_value method as mentioned in other posts, but it didn't work.</p>

<p>Thanks!</p>

<hr>

<p>Thanks for the vectorized approach, much cleaner! However, I get the following error, and the value is still not updating:</p>

<p><a href="https://i.stack.imgur.com/IjFSt.png" rel="nofollow"><img src="https://i.stack.imgur.com/IjFSt.png" alt="enter image description here"></a></p>

<p>According to <code>iterrows</code>documentation:</p>

<blockquote>
  <ol start="2">
  <li>You should <strong>never modify</strong> something you are iterating over.    This is not guaranteed to work in all cases. Depending on the    data
  types, the iterator returns a copy and not a view, and writing    to
  it will have no effect.</li>
  </ol>
</blockquote>

<p><code>row['UPC'] = ('0' + row['UPC'])</code> silently modifies a copy of the row, and <code>clean_data</code> is kept unmodified.</p>

<p>Do adopt a vectorized approach of your algorithm like @Gene is suggesting.</p>

python csv pandas dataframe