问题
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