Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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

like image 380
ssteyer Avatar asked Jun 23 '15 06:06

ssteyer


People also ask

How do I sum up a column in a data frame?

sum() to Sum All Columns. Use DataFrame. sum() to get sum/total of a DataFrame for both rows and columns, to get the total sum of columns use axis=1 param. By default, this method takes axis=0 which means summing of rows.

How do you sum up rows in a data frame?

To sum all the rows of a DataFrame, use the sum() function and set the axis value as 1. The value axis 1 will add the row values.


1 Answers

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))
like image 85
maxymoo Avatar answered Oct 10 '22 19:10

maxymoo