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>Can I suggest a different method? </p>

<pre><code>#identify the strings shorter than 11 characters
fix_indx = clean_data.UPC.astype(str).str.len()&lt;11

#append these strings with a '0'
clean_data.loc[fix_indx] = '0'+clean_data[fix_indx].astype(str)
</code></pre>

<p>To fix the others, you can similarly do:</p>

<pre><code>bad_length_indx = clean_data.UPC.astype(str).str.len()&gt;13
clean_data.loc[bad_length] = np.nan
</code></pre>

python csv pandas dataframe