划分下一行的值并在数据框中创建列 [英] divide value of next row and create column in dataframe
本文介绍了划分下一行的值并在数据框中创建列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似csv的
id,value
1,100
1,150
1,200
1,250
2,300
2,350
2,400
2,450
我想根据每个唯一ID的值生成一列.
I want to generate one column based on value of each of the unique id.
例如:
- id为1的前2行的值为100、150
- 我正在尝试创建列
raise
,该列将像这样划分值 - 100/100 = 1,所以带有加高列的第一行将有1
- 150/100 = 1.5,因此带有加高列的第二行将有2
- id 2相同
- 250/250 = 1和300/250 = 1.166
- 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
我取了100,因为它是该
id
的第一个值,与第二个'id'相同 例如:
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
所以最终我的输出将是
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
除了在所有id
中使用for循环外,我不知道如何创建它.
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
推荐答案
由GroupBy.transform
和
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
这篇关于划分下一行的值并在数据框中创建列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文