如何用Pandas计算两个数据帧之间的百分比差异?

问题描述 投票:0回答:2

我正在使用pandas,我执行一些计算和转换,最终我得到两个看起来或多或少像这样的数据框:

ID      'abc'     'def'
Total     4         5
Slow      0         0
Normal    1         2
Fast      3         3

ID      'abc'     'def'
Total     3         4
Slow      0         0
Normal    0         1
Fast      3         3

现在,给定这两个数据帧,我想生成第三个数据帧,它以某种方式返回第二个数据帧满足的第一个数据帧的百分比。这样我希望结果如下:

ID      'abc'     'dfe'
Total   75.0%      80.0%
Slow     None      None
Normal   0.0%      50.0%
Fast    100.0%     100.0%

如果第一个数据帧中有0,那么在结果数据帧中我们将该单元格设置为None或其他内容。整个想法是,最后我将结果写入Excel文件,因此我希望在Excel中具有None的单元格为空。有关如何使用pandas在Python中执行此操作的任何想法?

python pandas dataframe percentage calculation
2个回答
4
投票

你可以简单地将df2除以df1在感兴趣的列上:

df2.loc[:,"'abc'":] = df2.loc[:,"'abc'":].div(df1.loc[:,"'abc'":]).mul(100)

     ID     'abc'  'dfe'
0   Total   75.0   80.0
1    Slow    NaN    NaN
2  Normal    0.0   50.0
3    Fast  100.0  100.0

更新

要按指定格式化,您可以执行以下操作:

df2.loc[:,"'abc'":] = df2.where(df2.loc[:,"'abc'":].isna(), 
                                df2.round(2).astype(str).add('%'))

      ID    'abc'   'dfe'
0   Total   75.0%   80.0%
1    Slow     NaN     NaN
2  Normal    0.0%   50.0%
3    Fast  100.0%  100.0%

鉴于没有小数位,除了.0之外,round(2)对显示的浮点数没有影响,但是一旦在划分后有一些带有更多小数位的浮点数,您将看到所有浮点数的2小数位。


0
投票

熊猫提供了直接指定styling in the output excel file的一些可能性。这是有限的,但幸运的是,你确实包括一个数字格式选项。

import pandas as pd

# Initialize example dataframes
df1 = pd.DataFrame(
    data=[[4, 5], [0, 0], [1, 2], [3, 3], [3, 3]],
    index=['Total', 'Slow', 'Normal', 'Fast', 'Fast'],
    columns=['abc', 'def'],
)
df2 = pd.DataFrame(
    data=[[3, 4], [0, 0], [0, 1], [3, 3], [3, 3]],
    index=['Total', 'Slow', 'Normal', 'Fast', 'Fast'],
    columns=['abc', 'def'],
)

result_df = df2 / df1

# Change rows index into data column (to avoid any chance of having non-unique row index values,
# since the pandas styler can only handle unique row index)
result_df = result_df.reset_index()

# Write excel output file with number format styling applied
result_df.style.applymap(lambda _: 'number-format: 0.00%').to_excel('result.xlsx', engine='openpyxl', index=False)
© www.soinside.com 2019 - 2024. All rights reserved.