Python/Pandas - 在具有年份列名称的数据框中动态计算年度比率

标签 python pandas

我有这个数据框:

df:

     Co_Name  . 2014 Revenues . Address . 2012 Profits . 2014 Profits...
1 .  Apple      1231            Gjud St   20             23          ...
2 .  Orange     84894           Uinjs St  712            313         ...
3 .  Squirrel   9192            Iusaa St  4312           123         ...
...

例如:'2014 Revenues' 表示某公司在 2014 年的收入。

我需要计算不同的比率,用同一年的值制作方程式。比如我需要计算从2014年开始的利润率,也就是说:

df['2014 ProfitMg'] = df['2014 Profits']/df['2014 Revenues']

但是,我有很多年的时间和很多比率可以从这个数据框(巨大的数据框)中取出,所以我想以动态和 pythonic 的方式制作它。我想说:“Python 先生,请计算以相同的 4 个字符字符串开头的名为“Profits”和“Revenues”的列的 Profits/Revenues”或类似内容。

它应该是这样的:

     Co_Name  . 2014 Revenues . Address . 2012 Profits . 2014 Profits . 2014 ProfitMg  ...
1 .  Apple      1231            Gjud St   20             23             0.019
2 .  Orange     84894           Uinjs St  712            313            0.008
3 .  Squirrel   9192            Iusaa St  4312           123            0.0133
...

有人可以帮助以动态方式代替 df['2014 ProfitMg'] = df['2014 Profits']/df['2014 Revenues'] 吗?

最佳答案

当然,您可以找到匹配的列并将公式应用于它们:

import re
years = [re.findall(r"(\d{4})\sRevenues", col) for col in df.columns]
for year in years:
    if year:
        df['{} ProfitMg'.format(year[0])] = df['{} Profits'.format(year[0])]\
                                       / df['{} Revenues'.format(year[0])]

此解决方案假设每个“收入”列都有一个匹配的“利润”列。如果不是,则获取一组“利润”年份和一组“收入”年份并取它们的交集。

关于Python/Pandas - 在具有年份列名称的数据框中动态计算年度比率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45823808/

相关文章:

python - 在Python中根据键(而不是键值)过滤字典列表

python - 在 Python 中使用 OpenCv2 编写多个图像

python - h2o python 的 one_hot_explicit 参数引发错误

python - 选择两个数据框列之一作为新列的输入

python - 对 Pandas 中的分组数据应用文本解析

python - 转换为 html 表时删除 pandas 数据框中的索引

python - 有没有办法在类定义之后设置元类?

python - Pandas DataFrame 到列表列表

python - Pandas :计算子组内的百分位数?

python - 在 pandas 库中使用 .apply 并收到 "np not callable"错误