I would like to create a new column for my dataframe named "Id" where the value is the row index +1. I would like to be like the example below:
ID Col1 ...
0 1 a ...
1 2 b ...
2 3 c ...
In order to set index to column in pandas DataFrame use reset_index() method. By using this you can also set single, multiple indexes to a column. If you are not aware by default, pandas adds an index to each row of the pandas DataFrame.
You can select rows from a list index using index. isin() Method which is used to check each element in the DataFrame is contained in values or not.
To set a column as index for a DataFrame, use DataFrame. set_index() function, with the column name passed as argument. You can also setup MultiIndex with multiple columns in the index. In this case, pass the array of column names required for index, to set_index() method.
To promote the first row to column headers, select Home > Use First Row As Headers.
You can add one to the index and assign it to the id
column:
df = pd.DataFrame({"Col1": list("abc")})
df["id"] = df.index + 1
df
#Col1 id
#0 a 1
#1 b 2
#2 c 3
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