如何在Python中使用pct_change计算数据框中2列的百分比变化 [英] how to calculate percentage changes across 2 columns in a dataframe using pct_change in Python

查看:367
本文介绍了如何在Python中使用pct_change计算数据框中2列的百分比变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,并希望使用pct_chg方法计算所选列B和C中只有2个之间的百分比变化,并将输出放到新列中.下面的代码似乎不起作用.谁能帮我?

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']

推荐答案

尝试:

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

这篇关于如何在Python中使用pct_change计算数据框中2列的百分比变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆