pandas 计算比率作为枢轴中的值 table

pandas Calculating ratio as values in pivot table

我有一个看起来像这样的 Df:

    tests  Machine  results
    111    A        OK
    111    A        OK
    111    A        OK
    111    A        NOK
    111    B        OK
    222    A        OK
    333    A        OK
    333    B        OK
    444    A        OK
    222    A        NOK
    222    A        OK
    111    B        OK

我想要一个 matrix/pivot table,其中行应该是测试,列应该是机器,值应该是 ratio/percentage 的测试,这些测试对总测试数来说是可以的对于每台机器。

结果应该是:

   OK/total cnt  A     B
   111           75%   100%   #test 111 passed 3 out of 4 tests in machine A and all tests in B
   222           50%   0%     #test 222 passed 1 out of 2 tests in machine A and 0 tests prfrmd in B
   333           100%  100%   #test 333 passed all tests in A and B machines

请帮我解决这个问题。

DataFrame.assign with compare for OK by Series.eq, then pivoting by default mean method in DataFrame.pivot_table 创建新列,按 100 倍增,最后如有必要将索引转换为 column:

df = (df.assign(res = df['results'].eq('OK'))
        .pivot_table(index='tests',
                     columns='Machine', 
                     values='res', 
                     fill_value=0)
        .mul(100)
        .rename_axis(index='OK/total cnt', columns=None)
        .reset_index())
print (df)
   OK/total cnt           A    B
0           111   75.000000  100
1           222   66.666667    0
2           333  100.000000  100
3           444  100.000000    0

获取等于 OK 的行的列,然后 运行 一个 crosstab 以获得平均值

df = df.assign(passed=df.results.eq("OK"))

(
    pd.crosstab(df.tests, df.Machine, df.passed, aggfunc="mean")
    .rename_axis(columns=None, index="OK/total cnt")
    .mul(100, fill_value=0)
)

                  A           B
OK/total cnt        
  111           75.000000   100.0
  222           66.666667   0.0
  333          100.000000   100.0
  444          100.000000   0.0