Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create column named "Id" based on row index

Tags:

python

pandas

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     ...
like image 760
hdatas Avatar asked Dec 13 '16 15:12

hdatas


People also ask

How do I turn a DataFrame index into a column?

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.

How do you select rows based on index?

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.

How do I set an index column name?

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.

How do I turn first row into column names in pandas?

To promote the first row to column headers, select Home > Use First Row As Headers.


1 Answers

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
like image 196
Psidom Avatar answered Sep 21 '22 13:09

Psidom