英文:
how to calculate value using previous other columns' value in python
问题
我想从下面的DataFrame中计算回报率。
使用其他列的前一行,甚至按id
分组
具体来说,
从
>>> df = pd.DataFrame({'id': ['Blue', 'Blue','Blue','Red','Red'],
'a':[100,200,300,1,2],
'b':[10,20,15,3,2],
'c':[1,2,3,4,5]})
>>> df
id a b c
0 Blue 100 10 1
1 Blue 200 20 2
2 Blue 300 15 3
3 Red 1 3 4
4 Red 2 2 5
我想要做以下操作。
df['new_col'] = a / a(前一行的值) + b(前一行的值) - c(前一行的值)
我认为pct_change()
不会帮助,因为它只适用于同一列。
>>> df
id a b c new_col
0 Blue 100 10 1 -
1 Blue 200 20 2 = 200 / (100 + 10 - 1)
2 Blue 300 15 3 = 300 / (200 + 20 - 2)
3 Red 1 3 4 -
4 Red 2 2 5 = 2 / (1 + 3 - 4)
英文:
I'd like to calculate rate of return from Dataframe belows.
Using other columns' previous row, even group by id
To be specific ,
From
>>> df = pd.DataFrame({'id': ['Blue', 'Blue','Blue','Red','Red'],
'a':[100,200,300,1,2],
'b':[10,20,15,3,2],
'c':[1,2,3,4,5]})
>>> df
id a b c
0 Blue 100 10 1
1 Blue 200 20 2
2 Blue 300 15 3
3 Red 1 3 4
4 Red 2 2 5
I want to make following.
df['new_col'] = a / a(previous row value) + b(previous row value) - c(previous row value)
I think pct_change()
doen't help since it works only same column.
>>> df
id a b c new_col
0 Blue 100 10 1 -
1 Blue 200 20 2 = 200 / (100 + 10 - 1)
2 Blue 300 15 3 = 300 / (200 + 20 - 2)
3 Red 1 3 4 -
4 Red 2 2 5 = 2 / (1 + 3 - 4)
答案1
得分: 0
尝试:
def fn(g):
out = g['a'] / (g['a'].shift() + g['b'].shift() - g['c'].shift())
g['new_col'] = out
return g
df = df.groupby('id', group_keys=False).apply(fn)
print(df)
打印:
id a b c new_col
0 蓝色 100 10 1 NaN
1 蓝色 200 20 2 1.834862
2 蓝色 300 15 3 1.376147
3 红色 1 3 4 NaN
4 红色 2 2 5 inf
英文:
Try:
def fn(g):
out = g['a'] / (g['a'].shift() + g['b'].shift() - g['c'].shift())
g['new_col'] = out
return g
df = df.groupby('id', group_keys=False).apply(fn)
print(df)
Prints:
id a b c new_col
0 Blue 100 10 1 NaN
1 Blue 200 20 2 1.834862
2 Blue 300 15 3 1.376147
3 Red 1 3 4 NaN
4 Red 2 2 5 inf
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论