ssteyer
ssteyer

Reputation: 231

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

I have been running into this problem a lot. If you have an existing DataFrame in Pandas, and you want to add a row that is simply an increasing count, ie. 0, 1, 2..., what is the most efficient way to do it?

Thanks!

Sam

Upvotes: 17

Views: 26119

Answers (2)

GBGOLC
GBGOLC

Reputation: 600

If you want to set a specific starting point that's not zero based, say 100:

   initial_value = 100

   df['Counter'] = range(initial_value, len(df) +initial_value)

For negative numbering just multiply initial value by -1:

   initial_value = 100 * -1

   df['Counter'] = range(initial_value, len(df) +initial_value)

I

Upvotes: 4

maxymoo
maxymoo

Reputation: 36555

The easiest way might be

df = df.reset_index()

This will give you a new index starting at 0.

You could also do

df['counter'] = range(len(df))

Upvotes: 24

Related Questions