简体   繁体   中英

divide value of next row and create column in dataframe

I have one csv like

id,value
1,100
1,150
1,200
1,250
2,300
2,350
2,400
2,450

I want to generate one column based on value of each of the unique id.

For Example:

  • first 2 rows for id 1 has value 100, 150
  • i am trying to create column raise which will divide value like this
  • 100/100 = 1 so first row with in raise column will have 1
  • 150/100 = 1.5 so second row with in raise column will have 2
  • same for id 2
  • 250/250 = 1 and 300/250 = 1.166

I took 100 because its the first value for that id , same for the 2nd 'id' for example:

id,value
1,150
1,100
1,200
1,250

if this was the case then output should be

id,value,raise
1,150,150/150
1,100,100/150
1,200,200/150
1,250,250/150

so in the end my output will be like

   id  value  raise
0   1    100  1.000
1   1    150  1.500
2   1    200  2.000
3   1    250  2.500
4   2    300  1.000
5   2    350  1.166
6   2    400  1.333
7   2    450  1.500

I don't know how to create it except using for loop through all the id .

Not all the value has same interval it's just an example

Divide column by Series created by GroupBy.transform with GroupBy.first :

df['raise'] = df['value'].div(df.groupby('id')['value'].transform('first'))
print (df)
   id  value     raise
0   1    100  1.000000
1   1    150  1.500000
2   1    200  2.000000
3   1    250  2.500000
4   2    300  1.000000
5   2    350  1.166667
6   2    400  1.333333
7   2    550  1.833333

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM