group values in rows together and assign a interger value to them

Viewed 29

Hi I have dataframe that looks like this:

A B C D
AB X 10 1a
FH Y 15 4h
KY Z 20 6f
DA X 10 1a

I want to create a new column where an interger (starting from 1/0) is assigned to all rows that have same value in column B,C,D

for eg : row1,4 will be same integer in column 'Val' that is created.

Output should look something like this

A B C D Val
AB X 10 1a 1
FH Y 15 4h 2
KY Z 20 6f 3
DA X 10 1a 1
1 Answers

Use pd.factorize with a frozenset

df['Val'] = pd.factorize(df[['B', 'C', 'D']].apply(frozenset, axis=1))[0] + 1
print(df)

# Output
    A  B   C   D  Val
0  AB  X  10  1a    1
1  FH  Y  15  4h    2
2  KY  Z  20  6f    3
3  DA  X  10  1a    1
Related