Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change value of column based on specific id in pandas dataframe

I have the below sorted dataframe and I want to set the last value of each id in the id column to 0

id value
1   500
1   50
1   36
2   45
2   150
2   70
2   20
2   10

I am able to set the last value of the entire id column to 0 using df['value'].iloc[-1] = 0. How can I set the last value of both id : 1 and id : 2 to get the below output.

id value
1   500
1   50
1   0
2   45
2   150
2   70
2   20
2   0
like image 862
GKC Avatar asked Dec 22 '22 17:12

GKC


1 Answers

you can do drop_duplicates and keep last to get the last row of each id. Use the index of these rows and set the value to 0

df.loc[df['id'].drop_duplicates(keep='last').index, 'value'] = 0

print(df)
   id  value
0   1    500
1   1     50
2   1      0
3   2     45
4   2    150
5   2     70
6   2     20
7   2      0
like image 71
Ben.T Avatar answered Feb 01 '23 12:02

Ben.T