Python pandas dataframe, how to get the set number

Viewed 125

Here is eaxmple:

df=pd.DataFrame([('apple'),('apple'),('apple'),('orange'),('orange')],columns=['A'])

df
Out[5]: 
        A
0   apple
1   apple
2   apple
3  orange
4  orange

I want to assign a number next to it, example, apple is the first set of list ['apple','orange'], B column is 1, then 2 for orange:

        A   B
0   apple   1
1   apple   1
2   apple   1
3  orange   2
4  orange   2

Bellow wouldn't work.

df['B']=df['A'].tolist().index(df['A']) +1 
2 Answers

You can use the pd.factorize function. This function is used to convert arrays into categorical ones.

pd.Series.factorize is also available as a method of pd.Series objects:

codes, _ = df["A"].factorize()
df["B"] = codes + 1

print(df)
        A  B
0   apple  1
1   apple  1
2   apple  1
3  orange  2
4  orange  2

use groupby ngroup + 1 with sort=False to ensure groups are enumerated in the order they appear in the DataFrame:

df['B'] = df.groupby('A', sort=False).ngroup() + 1

df:

        A  B
0   apple  1
1   apple  1
2   apple  1
3  orange  2
4  orange  2
Related