Convert an Object dtype column to Number Dtype in a datafrane Pandas
<p>Trying to answer this question <a href="http://stackoverflow.com/questions/39647978/get-list-of-unique-string-values-per-column-in-a-dataframe-using-python">Get List of Unique String per Column</a> we ran into a different problem from my dataset. When I import this CSV file to the dataframe every column is OBJECT type, we need to convert the columns that are just number to real (number) dtype and those that are not number to String dtype.</p>

<p>Is there a way to achieve this?</p>

<p><a href="https://www.dropbox.com/s/thtxso04c1y13xl/HistorianDataSample.zip?dl=0" rel="nofollow">Download the data sample from here</a></p>

<p>I have tried following code from following article <a href="http://stackoverflow.com/questions/15891038/pandas-change-data-type-of-columns">Pandas: change data type of columns</a> but did not work.</p>

<pre><code>df = pd.DataFrame(a, columns=['col1','col2','col3'])
</code></pre>

<p>As always thanks for your help</p>

<p><strong><em>Option 1</em></strong><br>
use <code>pd.to_numeric</code> in an <code>apply</code></p>

<pre><code>df.apply(pd.to_numeric, errors='ignore')
</code></pre>

<p><strong><em>Option 2</em></strong><br>
use <code>pd.to_numeric</code> on <code>df.values.ravel</code></p>

<pre><code>cvrtd = pd.to_numeric(df.values.ravel(), errors='coerce').reshape(-1, len(df.columns))
pd.DataFrame(np.where(np.isnan(cvrtd), df.values, cvrtd), df.index, df.columns)
</code></pre>

<hr>

<p><strong><em>Note</em></strong><br>
These are not exactly the same.  For some column that contains mixed values, option 2 converts what it can while option 2 leaves everything in that column an object.  Looking at your file, I'd choose option 1.</p>

<hr>

<p><strong><em>Timing</em></strong>  </p>

<pre><code>df = pd.read_csv('HistorianDataSample/HistorianDataSample.csv', skiprows=[1, 2])
</code></pre>

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

python pandas