0

I have a dataframe that looks like this

Name  a   
b     4   
c     4    
d     4 

I want to subtract a number from each row in column a, that number is given by an arithmetic sequence (x=x+1) and starts from 1, hence the result will be the below.

Name  a   
b     3   
c     2    
d     1 

How can this be achieved?

Artem
  • 29
  • 1
  • 2

1 Answers1

2

Use Series.sub with np.arange:

df['a'] = df['a'].sub(np.arange(1, len(df) + 1))
#df['a'] = df['a'] - np.arange(1, len(df) + 1)

or if default index:

df['a'] = df['a'].sub(df.index + 1)

Output

  Name  a
0    b  3
1    c  2
2    d  1

we could also do:

df['a'] -= df.index + 1
df['a'] -= np.arange(1, len(df)+1)
ansev
  • 30,322
  • 5
  • 17
  • 31