modifying many columns in pandas dataframe
<p>I have been stuck on this for a while and no amount of googling seems to help. </p>

<p>I am reading in a lot of raw data. Some of the variables come in as objects due to the source using letters for various reasons for missing (which I do not care about).</p>

<p>So I want to run a fairly large subset of columns through <code>pandas.to_numeric(___ ,error='coerce')</code> just to force these to be cast as int or float (again, I do not care too much which, just that they are numeric.</p>

<p>I can make this happen column by column easy:</p>

<pre><code>df['col_name'] = pd.to_numeric(df['col_name'], errors='coerce') 
</code></pre>

<p>However, I have some 60 columns I want to cast like this .. so I thought this would work:</p>

<pre><code>numeric = ['lots', 'a', 'columns']
for item in numeric:
    df_[item] = pd.to_numeric(df[item], errors='coerce')
</code></pre>

<p>The error I get is:</p>

<pre><code>Traceback (most recent call last):

File "/Users/____/anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2885, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)

File "&lt;ipython-input-53-43b873fbd712&gt;", line 2, in &lt;module&gt;
df_detail[item] = pd.to_numeric(dfl[item], errors='coerce')

File "/Users/____/anaconda/lib/python2.7/site-packages/pandas/tools/util.py", line 101, in to_numeric
raise TypeError('arg must be a list, tuple, 1-d array, or Series')

TypeError: arg must be a list, tuple, 1-d array, or Series
</code></pre>

<p>I tried many versions. This is has something to do with the list or looking through it. I get the very same error when the for-loop simply calls for <code>df(item).describe()</code> </p>

<p>From my (still novice) understanding of Python, this should work. I am at loss.
Thanks</p>

<p>First of all, see <a href="http://stackoverflow.com/a/39801222/2336654">this answer</a></p>

<pre><code># Let
numeric = ['lots', 'a', 'columns']
</code></pre>

<p><strong><em>Option 1</em></strong></p>

<pre><code>df[numeric] = df[numeric].apply(pd.to_numeric, errors='coerce')
</code></pre>

<p><strong><em>Option 2</em></strong></p>

<pre><code>df.loc[:, numeric] = pd.to_numeric(df[numeric].values.ravel(), 'coerce') \
                       .reshape(-1, len(numeric))
</code></pre>

<p><strong><em>Demonstration</em></strong><br>
Consider the dataframe <code>df</code></p>

<pre><code>df = pd.DataFrame([
        [1, 'a', 2],
        ['b', 3, 'c'],
        ['4', 'd', '5']
    ], columns=['A', 'B', 'C'])
</code></pre>

<p>Then both <strong><em>options</em></strong> above yield</p>

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

python list pandas dataframe