How to add a simple counter column that increments by one in each row to a Pandas DataFrame?

I often came across this problem. If you have an existing DataFrame in Pandas and you want to add a row that just increments the score, i.e. 0, 1, 2 ... what is the most efficient way to do this?

Thank!

Sam

+4
source share
1 answer

The easiest way -

df = df.reset_index()

This will give you a new index starting at 0.

You can also do

df['counter'] = range(len(df))
+7
source

All Articles