how to calculate percentage changes across 2 columns in a dataframe using pct_change in Python

冷暖自知 提交于 2019-12-02 12:36:44

Try:

df2['new'] = df2[['B','C']].pct_change(axis=1)['C']

pct_change returns pct_change across all the columns, you can select the required column and assign to a new variable.

df2['new'] = df2.pct_change(axis=1)['C']


    A   B   C   D   new
0   29  4   29  5   6.250000
1   14  35  2   40  -0.942857
2   5   18  31  10  0.722222
3   17  10  42  41  3.200000
4   24  48  47  35  -0.020833

IIUC, you can just do the following:

df2['new'] = (df2['C']-df2['B'])/df2['B']
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!