Decreasing column values with Pandas

Question:

I would like to decrease values in a column. The following code

df['ID'] = df.index
df.loc[df['ID'].astype(int)] -= 1

Should convert

   ID  Process ID Name     Time
0   0         NaN  NaN  msecond
1   1     32434.0   X1      1.4
2   2     32434.0   X2      1.3

to

   ID  Process ID Name     Time
0  -1         NaN  NaN  msecond
1   0     32434.0   X1      1.4
2   1     32434.0   X2      1.3

How can I fix that? I should keep the first line because of the code I have written.

Asked By: mahmood

||

Answers:

Subtract ID only:

#if necessary convert to integers
#df['ID'] = df['ID'].astype(int)
df['ID'] -= 1

Or maybe:

df['ID'] = df.index - 1

For first column:

df.insert(0, 'ID', df.index - 1)
Answered By: jezrael
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.