Home > Mobile >  Pandas - Adding auto - increment value to Dataframe
Pandas - Adding auto - increment value to Dataframe

Time:09-17

I have a Dataframe in which I would like to add a new column that has numbers added to it as a column in increments. This is more like a id (with an incremental update)

However I would like this id column to start from value stored in a variable called max_id

df['id'] = [x for x in range(max_id, max_id   len(df)   1)]

This throws an error

ValueError: Length of values (7649) does not match length of index (7648)

For example if max_id value is 100, I would like the df['id'] to start from 101 and go on for how many ever rows are there in the Dataframe

CodePudding user response:

I am not sure if I get you, but you could just use np.arange:

df['id'] = np.arange(max_id   1, max_id   len(df)   1)

Or:

df['id'] = np.arange(max_id, max_id   len(df))   1

CodePudding user response:

You can try using pd.RangeIndex.

df['id'] = pd.RangeIndex(max_id, max_id   len(df))   1
  • Related