Turning a column of rows into a column of integers in Pandas

I am trying to turn a column of rows into integer identifiers ... and I cannot find an elegant way to do this in pandas (or python). In the following example, I convert "A", which is a column / variable of rows, to numbers through matching, but it looks like a dirty hack for me.

import pandas as pd                                                                             
import numpy as np

df = pd.DataFrame({'A': ['homer_simpson', 'mean_street', 'homer_simpson', 'bla_bla'], 'B': 4})

unique = df['A'].unique()
mapping = dict(zip(unique, np.arange(len(unique))))

new_df = df.replace({'A': mapping})

Is there a better, more direct way to achieve this?

+4
source share
4 answers

How about using factorize?

>>> labels, uniques = df.A.factorize()
>>> df.A = labels
>>> df
   A  B
0  0  4
1  1  4
2  0  4
3  2  4

http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.factorize.html

+5
source

, . , .

df['A'] = df.A.map({val: n for n, val in enumerate(df['A'].unique())})

>>> df
   A  B
0  0  4
1  1  4
2  0  4
3  2  4
+1

Assuming you care about what integers are, just for consistent matching, you could (1) use categorical codes or (2) rank values:

>>> df["A_categ"] = pd.Categorical(df.A).codes
>>> df["A_rank"] = df["A"].rank("dense").astype(int)
>>> df
               A  B  A_categ  A_rank
0  homer_simpson  4        1       2
1    mean_street  4        2       3
2  homer_simpson  4        1       2
3        bla_bla  4        0       1
0
source

Sorry, I don’t have enough reputation points for comment (new here). I just want to know if using a Dataframe join will be faster than this:

df.merge(df.drop_duplicates().reset_index(),on="A")["index"]
0
source

Source: https://habr.com/ru/post/1620498/


All Articles