MEhsan MEhsan - 3 months ago 42
Python Question

How to Add Incremental Numbers to a New Column Using Pandas

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!

Answer

Here:

df = df.reset_index()
df.columns[0] = 'New_ID'
df['New_ID'] = df.index + 880