pandas.DataFrame set all string values to nan
<p>I have a <code>pandas.DataFrame</code> that contain string, float and int types.</p>

<p>Is there a way to set all strings that cannot be converted to float to <code>NaN</code> ?</p>

<p>For example:</p>

<pre class="lang-py prettyprint-override"><code>    A  B   C      D
0   1  2   5      7
1   0  4 NaN     15
2   4  8   9     10
3  11  5   8      0
4  11  5   8  "wajdi"
</code></pre>

<p>to:</p>

<pre class="lang-py prettyprint-override"><code>    A  B   C      D
0   1  2   5      7
1   0  4 NaN     15
2   4  8   9     10
3  11  5   8      0
4  11  5   8    NaN
</code></pre>

<p>You can use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.to_numeric.html" rel="nofollow"><code>pd.to_numeric</code></a> with <code>errors='coerce'</code>. </p>

<pre><code>In [30]: df = pd.DataFrame({'a': [1, 2, 'NaN', 'bob', 3.2]})

In [31]: pd.to_numeric(df.a, errors='coerce')
Out[31]: 
0    1.0
1    2.0
2    NaN
3    NaN
4    3.2
Name: a, dtype: float64
</code></pre>

<p>Here is one way to apply it to all columns:</p>

<pre><code>for c in df.columns:
    df[c] = pd.to_numeric(df[c], errors='coerce')
</code></pre>

<p>(See comment by NinjaPuppy for a better way.)</p>

python string pandas dataframe