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

瘦欲@ 提交于 2019-12-31 05:40:08

问题


I have a dataframe and want to use pct_chg method to calculate the % change between only 2 of the selected columns, B and C, and put the output into a new column. the below code doesnt seem to work. can anyone help me?

df2 = pd.DataFrame(np.random.randint(0,50,size=(100, 4)), columns=list('ABCD'))

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


回答1:


Try:

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



回答2:


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



回答3:


IIUC, you can just do the following:

df2['new'] = (df2['C']-df2['B'])/df2['B']


来源:https://stackoverflow.com/questions/56138674/how-to-calculate-percentage-changes-across-2-columns-in-a-dataframe-using-pct-ch

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