python: generate numeric column to column with string
<p>I have a dataframe and it's a part of a column</p>

<pre><code>category
Search
Search
ÐÐ½Ð»Ð°Ð¹Ð½-Ð¼Ð°Ð³Ð°Ð·Ð¸Ð½
ÐÐ½Ð»Ð°Ð¹Ð½-Ð¼Ð°Ð³Ð°Ð·Ð¸Ð½
Ð¤Ð¾ÑÑÐ¼Ñ Ð¸ Ð¾ÑÐ·ÑÐ²Ñ
ÐÐ½Ð»Ð°Ð¹Ð½-Ð¼Ð°Ð³Ð°Ð·Ð¸Ð½
Ð¤Ð¾ÑÑÐ¼Ñ Ð¸ Ð¾ÑÐ·ÑÐ²Ñ
ÐÐ³ÑÐµÐ³Ð°ÑÐ¾Ñ
ÐÐ½ÑÐ¾ÑÐ¼Ð°ÑÐ¸Ð¾Ð½Ð½ÑÐ¹ ÑÐµÑÑÑÑ
ÐÐ½Ð»Ð°Ð¹Ð½-Ð¼Ð°Ð³Ð°Ð·Ð¸Ð½
Ð¢ÐµÐ»ÐµÐºÐ¾Ð¼
ÐÐ½Ð»Ð°Ð¹Ð½-Ð¼Ð°Ð³Ð°Ð·Ð¸Ð½
</code></pre>

<p>I need to create column with category, converted to numeric.
I mean</p>

<pre><code>category   numeric_category
Search     1
Search     1
ÐÐ½Ð»Ð°Ð¹Ð½-Ð¼Ð°Ð³Ð°Ð·Ð¸Ð½    2
ÐÐ½Ð»Ð°Ð¹Ð½-Ð¼Ð°Ð³Ð°Ð·Ð¸Ð½    2
Ð¤Ð¾ÑÑÐ¼Ñ Ð¸ Ð¾ÑÐ·ÑÐ²Ñ   3
ÐÐ½Ð»Ð°Ð¹Ð½-Ð¼Ð°Ð³Ð°Ð·Ð¸Ð½    2
Ð¤Ð¾ÑÑÐ¼Ñ Ð¸ Ð¾ÑÐ·ÑÐ²Ñ   3
ÐÐ³ÑÐµÐ³Ð°ÑÐ¾Ñ   4
ÐÐ½ÑÐ¾ÑÐ¼Ð°ÑÐ¸Ð¾Ð½Ð½ÑÐ¹ ÑÐµÑÑÑÑ   5
ÐÐ½Ð»Ð°Ð¹Ð½-Ð¼Ð°Ð³Ð°Ð·Ð¸Ð½   2
Ð¢ÐµÐ»ÐµÐºÐ¾Ð¼   6
ÐÐ½Ð»Ð°Ð¹Ð½-Ð¼Ð°Ð³Ð°Ð·Ð¸Ð½   2
</code></pre>

<p>How can I do that? using <code>numpy</code>?</p>

<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="nofollow"><code>factorize</code></a>:</p>

<pre><code>df['numeric_category'] = pd.factorize(df.category)[0] + 1
</code></pre>

<p>Then you can also convert it to <code>category</code> for saving memory:</p>

<pre><code>df['numeric_category'] = pd.Categorical(pd.factorize(df.category)[0] + 1)
</code></pre>

<p>Sample:</p>

<pre><code>df = pd.DataFrame({'category':['a','s','a']})
print (df)
  category
0        a
1        s
2        a

df['numeric_category'] = pd.Categorical(pd.factorize(df.category)[0] + 1)
print (df)
  category numeric_category
0        a                1
1        s                2
2        a                1
</code></pre>

python pandas