How to Add Incremental Numbers to a New Column Using Pandas

PythonPandasDataframe

Python Problem Overview


I have this simplified dataframe:

ID   Fruit
F1   Apple
F2   Orange
F3   Banana 

I want to add in the begining of the dataframe a new column df['New_ID'] which has the number 880 that increments by one in each row.

The output should be simply like:

New_ID   ID   Fruit
880      F1   Apple
881      F2   Orange
882      F3   Banana  

I tried the following:

df['New_ID'] = ["880"] # but I want to do this without assigning it the list of numbers literally

Any idea how to solve this?

Thanks!

Python Solutions


Solution 1 - Python

df.insert(0, 'New_ID', range(880, 880 + len(df)))
df

enter image description here

Solution 2 - Python

Here:

df = df.reset_index()
df = df.rename(columns={"index":"New_ID"})
df['New_ID'] = df.index + 880

Solution 3 - Python

You can also simply set your pandas column as list of id values with length same as of dataframe.

df['New_ID'] = range(880, 880+len(df))

Reference docs : https://pandas.pydata.org/pandas-docs/stable/missing_data.html

Solution 4 - Python

df = df.assign(New_ID=[880 + i for i in xrange(len(df))])[['New_ID'] + df.columns.tolist()]

>>> df
   New_ID  ID   Fruit
0     880  F1   Apple
1     881  F2  Orange
2     882  F3  Banana

Solution 5 - Python

I used the follow code:

df.insert(0, 'id', range(1, 1 + len(df)))

So my "id" columns is:

1, 2, 3, ...

Solution 6 - Python

For a pandas DataFrame whose index starts at 0 and increments by 1 (i.e., the default values) you can just do:

df.insert(0, 'New_ID', df.index + 880)

if you want New_ID to be the first column. Otherwise this if you don't mind it being at the end:

df['New_ID'] = df.index + 880

Solution 7 - Python

import numpy as np

df['New_ID']=np.arange(880,880+len(df.Fruit))
df=df.reindex(columns=['New_ID','ID','Fruit'])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMEhsanView Question on Stackoverflow
Solution 1 - PythonpiRSquaredView Answer on Stackoverflow
Solution 2 - PythonKartikView Answer on Stackoverflow
Solution 3 - PythonnamanView Answer on Stackoverflow
Solution 4 - PythonAlexanderView Answer on Stackoverflow
Solution 5 - PythonJoselin CeronView Answer on Stackoverflow
Solution 6 - PythonsnarkView Answer on Stackoverflow
Solution 7 - PythonBahati FelixView Answer on Stackoverflow