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!
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.
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.
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.
df.insert(0, 'New_ID', range(880, 880 + len(df))) df
Here:
df = df.reset_index() df = df.rename(columns={"index":"New_ID"}) df['New_ID'] = df.index + 880
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With