Pandas cast all object columns to category
<p>I want to have ha elegant function to cast all object columns in a pandas data 
frame to categories</p>

<p><code>df[x] = df[x].astype("category")</code> performs the type cast
<code>df.select_dtypes(include=['object'])</code> would sub-select all categories columns. However this results in a loss of the other columns / a manual merge is required. Is there a solution which "just works in place" or does not require a manual cast?</p>

<h1>edit</h1>

<p>I am looking for something similar as <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.convert_objects.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.convert_objects.html</a> for a conversion to categorical data</p>

<p>use <code>apply</code> and <code>pd.Series.astype</code> with <code>dtype='category'</code></p>

<p>Consider the <code>pd.DataFrame</code> <code>df</code></p>

<pre><code>df = pd.DataFrame(dict(
        A=[1, 2, 3, 4],
        B=list('abcd'),
        C=[2, 3, 4, 5],
        D=list('defg')
    ))
df
</code></pre>

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

<pre><code>df.info()

&lt;class 'pandas.core.frame.DataFrame'&gt;
RangeIndex: 4 entries, 0 to 3
Data columns (total 4 columns):
A    4 non-null int64
B    4 non-null object
C    4 non-null int64
D    4 non-null object
dtypes: int64(2), object(2)
memory usage: 200.0+ bytes
</code></pre>

<p>Lets use <code>select_dtypes</code> to include all <code>'object'</code> types to convert and recombine with a <code>select_dtypes</code> to exclude them.</p>

<pre><code>df = pd.concat([
        df.select_dtypes([], ['object']),
        df.select_dtypes(['object']).apply(pd.Series.astype, dtype='category')
        ], axis=1).reindex_axis(df.columns, axis=1)

df.info()

&lt;class 'pandas.core.frame.DataFrame'&gt;
RangeIndex: 4 entries, 0 to 3
Data columns (total 4 columns):
A    4 non-null int64
B    4 non-null category
C    4 non-null int64
D    4 non-null category
dtypes: category(2), int64(2)
memory usage: 208.0 bytes
</code></pre>

python pandas casting categorical-data