我有以下数据帧

#Example for Stackoverflow
df = pd.DataFrame({'Ticker': ['AAPL', 'MSFT', 'IBM'],
                   'totalRevenue_ttm': [386017000000, 192557000000, 50608000000],
                   'revenues_2021': [365817000000, 168088000000, 57351000000],
                   'revenues_2020': [274515000000, 143015000000, 55179000000],
                   'revenues_2019': [260174000000, 125843000000, 57714000000],
                   'revenues_2018': [265595000000, 110360000000, 79591000000]})

我想计算2021、2020年和2019年的销售额增长率.

如果我使用以下代码,我得到了2021的增长率

col=2
df[str(revenues.columns[col]) + "_Growth"]=(df.iloc[:, col]-revenues.iloc[:, col+1])/df.iloc[:, col+1]
df

The result looks like: enter image description here

我如何迭代这些列,以便也可以计算revenues\u 2020\u增长和revenues\u 2019\u增长

谢谢你的帮助,我非常感激.

推荐答案

您可以在列上使用pct_change:

out = (df.filter(regex='revenues_\d+').sort_index(axis=1, ascending=False)
         .pct_change(-1, axis=1).round(2)
         .iloc[:,1:].add_suffix('_Growth')
       )

输出:

   revenues_2021_Growth  revenues_2020_Growth  revenues_2019_Growth
0                  0.33                  0.06                 -0.02
1                  0.18                  0.14                  0.14
2                  0.04                 -0.04                 -0.27

结合输入:

out = df.join(df
 .filter(regex='revenues_\d+').sort_index(axis=1, ascending=False)
 .pct_change(-1, axis=1).round(2)
 .iloc[:,:-1].add_suffix('_Growth')
)

输出:

  Ticker  totalRevenue_ttm  revenues_2021  revenues_2020  revenues_2019  revenues_2018  revenues_2021_Growth  revenues_2020_Growth  revenues_2019_Growth
0   AAPL      386017000000   365817000000   274515000000   260174000000   265595000000                  0.33                  0.06                 -0.02
1   MSFT      192557000000   168088000000   143015000000   125843000000   110360000000                  0.18                  0.14                  0.14
2    IBM       50608000000    57351000000    55179000000    57714000000    79591000000                  0.04                 -0.04                 -0.27

Python相关问答推荐

如何在Pandas 中存储二进制数?

使用decorator 重复超载

将嵌套列表的字典转换为数据框中的行

从DataFrame.apply创建DataFrame

如何处理嵌套的SON?

运行总计基于多列pandas的分组和总和

_repr_html_实现自定义__getattr_时未显示

在Pandas DataFrame操作中用链接替换'方法的更有效方法

根据二元组列表在pandas中创建新列

在Mac上安装ipython

如果条件不满足,我如何获得掩码的第一个索引并获得None?

如何在WSL2中更新Python到最新版本(3.12.2)?

如何根据一列的值有条件地 Select 前N个组,然后按两列分组?

如果满足某些条件,则用另一个数据帧列中的值填充空数据帧或数组

为什么Django管理页面和我的页面的其他CSS文件和图片都找不到?'

合并帧,但不按合并键排序

与命令行相比,相同的Python代码在Companyter Notebook中运行速度慢20倍

使用BeautifulSoup抓取所有链接

Polars Group by描述扩展

以异步方式填充Pandas 数据帧