Convert float to int and leave nulls
<p>I have the following dataframe, I want to convert values in column 'b' to integer</p>

<pre><code>    a   b       c
0   1   NaN     3
1   5   7200.0  20
2   5   580.0   20
</code></pre>

<p>The following code is throwing exception 
"ValueError: Cannot convert NA to integer"</p>

<pre><code>df['b'] = df['b'].astype(int)
</code></pre>

<p>How do i convert only floats to int and leave the nulls as is?</p>

<p><code>np.NaN</code> is a floating point only kind of thing, so it has to be removed in order to create an integer pd.Series. Jeon's suggestion work's great If 0 isn't a valid value in <code>df['b']</code>. For example:</p>

<pre><code>import pandas as pd
import numpy as np

df = pd.DataFrame({'a': [1, 5, 5], 'b': [np.NaN, 7200.0, 580.0], 'c': [3, 20, 20]})
print(df, '\n\n')

df['b'] = np.nan_to_num(df['b']).astype(int)

print(df)
</code></pre>

<p>if there are valid 0's, then you could first replace them all with some unique value (e.g., -999999999), the the conversion above, and then replace these unique values with 0's.</p>

<p>Either way, you have to remember that you have 0's where there were once NaNs. You will need to be careful to filter these out when doing various numerical analyses (e.g., mean, etc.)</p>

python pandas numpy