擅长:python、mysql、java
<p>首先,要将分类列转换为其数字代码,您可以使用:<code>dataframe['c'].cat.codes</code>.<br/>
此外,还可以使用<code>select_dtypes</code>自动选择数据帧中具有特定数据类型的所有列。这样,您可以对多个自动选择的列应用上述操作。</p>
<p>首先制作一个示例数据帧:</p>
<pre><code>In [75]: df = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':list('abcab'), 'col3':list('ababb')})
In [76]: df['col2'] = df['col2'].astype('category')
In [77]: df['col3'] = df['col3'].astype('category')
In [78]: df.dtypes
Out[78]:
col1 int64
col2 category
col3 category
dtype: object
</code></pre>
<p>然后使用<code>select_dtypes</code>选择列,然后对每个列应用<code>.cat.codes</code>,可以得到以下结果:</p>
<pre><code>In [80]: cat_columns = df.select_dtypes(['category']).columns
In [81]: cat_columns
Out[81]: Index([u'col2', u'col3'], dtype='object')
In [83]: df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes)
In [84]: df
Out[84]:
col1 col2 col3
0 1 0 0
1 2 1 1
2 3 2 0
3 4 0 1
4 5 1 1
</code></pre>