1

I want to add a column with incremental numbers for rows with the same value in a defined row;

e.g. if I would have this df

df=pd.DataFrame([['a','b'],['a','c'],['c','b']])

and I want incremental numbers for the first column. It should look like this

df=pd.DataFrame([['a','b',1],['a','c',2],['c','b',1]])

I found sql solutions but I'm working with ipython/pandas. Can someone help me?

1 Answer 1

2

Use cumcount, for name of new column use length of original columns:

print (len(df.columns))
2

df[len(df.columns)] = df.groupby(0).cumcount() + 1
print (df)
   0  1  2
0  a  b  1
1  a  c  2
2  c  b  1
Sign up to request clarification or add additional context in comments.

1 Comment

Glad can help, nice day!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.