someone
someone

Reputation: 27

How to create a new column based on information in another column?

I try to create a new column in panda dataframe. I have names in one column, I want to attain numbers to them in a new column. If name is repeated sequentially, they get the same number, if they are repeated after different names then they should get another number

For example, my df is like

Name/
Stephen
Stephen
Mike 
Carla
Carla
Stephen

my new column should be

Numbers/
0
0
1
2
2
3

Sorry, I couldn't paste my dataframe here.

Upvotes: 1

Views: 56

Answers (1)

Scott Boston
Scott Boston

Reputation: 153500

Try:

df['Numbers'] = (df['Name'] != df['Name'].shift()).cumsum() - 1

Output:

      Name  Numbers
0  Stephen        0
1  Stephen        0
2     Mike        1
3    Carla        2
4    Carla        2
5  Stephen        3

Upvotes: 1

Related Questions