擅长:python、mysql、java
<p>如果你只担心你做了一个额外的专栏,然后删除它,只要不使用一个新的专栏在第一时间。</p>
<pre><code>dataframe = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':list('abcab'), 'col3':list('ababb')})
dataframe.col3 = pd.Categorical.from_array(dataframe.col3).codes
</code></pre>
<p>你完了。现在由于<code>Categorical.from_array</code>已被弃用,请直接使用<code>Categorical</code></p>
<pre><code>dataframe.col3 = pd.Categorical(dataframe.col3).codes
</code></pre>
<p>如果还需要从索引到标签的映射,还有更好的方法</p>
<pre><code>dataframe.col3, mapping_index = pd.Series(dataframe.col3).factorize()
</code></pre>
<p>在下面检查</p>
<pre><code>print(dataframe)
print(mapping_index.get_loc("c"))
</code></pre>