python apply function to df pandas - atribute error
<p>I have a data frame "b" with numbers stored as text like '12.5%'. 
One column is:</p>

<pre><code>1       NaN
2       NaN
3      1.2%
4      0.6%
5       NaN
6      1.4%
7      0.1%
8       NaN
9      5.1%
10     2.5%
11    89.1%
12      NaN
Name: Idaho, dtype: object
</code></pre>

<p>I've wrote a function to apply to each column:</p>

<pre><code>def sinPorc(tbl):
    return float(tbl.replace('%', ''))
</code></pre>

<p>but when I try to apply it I get:</p>

<pre><code>b.Idaho.apply(sinPorc)
</code></pre>

<blockquote>
  <p>AttributeError: 'float' object has no attribute 'replace'</p>
</blockquote>

<p>I 've also created an example table, and apply the function but in this case worked:</p>

<pre><code>ejemplo=pd.DataFrame({'A':['1.3%', 'NaN'],
              'B':['1.3%', '0.7%']})

ejemplo.A.apply(sinPorc)
</code></pre>

<p>and I got the expected result:</p>

<pre><code>    1.3
    NaN
Name: A, dtype: float64
</code></pre>

<p>I don't know why I cannot apply the function to the original table. What might be the problem and what should I do to solve it?</p>

<p>Thanks.</p>

<p>Your original method didn't work because NaN was not a string, but the float value <code>np.NaN</code> </p>

<p>Try this... </p>

<pre><code>np.NaN.replace('%', '')
</code></pre>

<p>and you will get the same error.</p>

<pre><code>AttributeError: 'float' object has no attribute 'replace'
</code></pre>

<p>You could change <code>sinPorc</code> to</p>

<pre><code>def sinPorc(tbl):
    if tbl is np.NaN:
        return tbl
    else:
        return float(tbl.replace('%', ''))
</code></pre>

<p>Which will preserver your <code>NaN</code> values which are useful for other Pandas functionality, or you could force the value to a string like Nickil mentioned in the comments.</p>

<pre><code>float(str(tbl).replace('%', ''))
</code></pre>

python function pandas attributes apply