Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 897
MEhsan Avatar asked Aug 10 '16 00:08

MEhsan


People also ask

How do you add a numerical index to a DataFrame?

set_index() is used to set a new index to the DataFrame. It is also used to extend the existing DataFrame, i.e., we can update the index by append to the existing index. We need to use the append parameter of the DataFrame. set_index() function to append the new index to the existing one.

How do I append to a column in pandas?

In pandas you can add/append a new column to the existing DataFrame using DataFrame. insert() method, this method updates the existing DataFrame with a new column. DataFrame. assign() is also used to insert a new column however, this method returns a new Dataframe after adding a new column.

How do you add a column ID in Python?

To add an identifier column, we need to specify the identifiers as a list for the argument “keys” in concat() function, which creates a new multi-indexed dataframe with two dataframes concatenated. Now we'll use reset_index to convert multi-indexed dataframe to a regular pandas dataframe.


2 Answers

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

enter image description here

like image 90
piRSquared Avatar answered Sep 27 '22 22:09

piRSquared


Here:

df = df.reset_index() df = df.rename(columns={"index":"New_ID"}) df['New_ID'] = df.index + 880 
like image 44
Kartik Avatar answered Sep 27 '22 22:09

Kartik