msa
msa

Reputation: 725

create new pandas column starting at 0

I have created a new column in pandas called 'index', which incrementally adds a number for each row.

idx = 0
df.insert(idx, 'index', value=range(1,len(df)+ 1))

However, my index currently starts at 1 and I would like to change it to start at 0.

Current Output:

'index'
    1
    2
    3
    4
    5
  ...

How would I do this?

Upvotes: 1

Views: 2995

Answers (1)

jezrael
jezrael

Reputation: 863166

Use range(df):

idx = 0
df.insert(idx, 'index', value=range(len(df)))

Or for better performance:

df.insert(idx, 'index', value=np.arange(len(df)))

If want add column to last one:

df = df.assign('index', value=np.arange(len(df)))

df['index'] = np.arange(len(df)

But if want select this column is necessary use []:

print (df['index'])

because with dot notation it select index:

print (df.index)

Upvotes: 4

Related Questions