如何仅将公式应用于 Pandas 中数据透视表 table 的某些行?

How to apply formula to only certain rows of pivot table in Pandas?

原版df我有:

    year security_software  usage
0   2006        anti_virus     77
1   2006          firewall     64
2   2006  security_updates     59
3   2007        anti_virus     84
4   2007          firewall     71
5   2007  security_updates     52
6   2008        anti_virus     91
7   2008          firewall     81
8   2008  security_updates     63
9   2009        anti_virus     90
10  2009          firewall     83
11  2009  security_updates     61
12  2010        anti_virus     90
13  2010          firewall     85
14  2010  security_updates     67
15  2011        anti_virus     89
16  2011          firewall     84
17  2011  security_updates     61
18  2012        anti_virus     83
19  2012          firewall     72
20  2012  security_updates     52
21  2013        anti_virus     84
22  2013          firewall     71
23  2013  security_updates     75
24  2014        anti_virus     81
25  2014          firewall     69
26  2014  security_updates     79
27  2015        anti_virus     80
28  2015          firewall     61
29  2015  security_updates     79

我为我的数据创建了一个数据透视表 table,并使用以下命令为其添加了一个 "Total" 行。

sec_pivot = df.pivot(index="security_software",columns='year',values = "usage")
sec_pivot.loc['Total'] = sec_pivot.sum()
print(sec_pivot)

year security_software  2006  2007  2008  2009  2010  2011  2012  2013  2014  2015
0           anti_virus    77    84    91    90    90    89    83    84    81    80
1             firewall    64    71    81    83    85    84    72    71    69    61
2     security_updates    59    52    63    61    67    61    52    75    79    79

如何在不影响 "Total" 行本身的情况下,将所有使用聚合更改为总值的百分比?

您可以将 loc 与索引切片一起使用

sec_pivot.loc["anti_virus":"security_updates"]/sec_pivot.loc["Total"] * 100

year                2006    2007        2008    
security_software           
anti_virus          38.5    40.579710   38.723404
firewall            32.0    34.299517   34.468085
security_updates    29.5    25.120773   26.808511

如果要替换原始 df 中的值,只需重新赋值

sec_pivot.loc["anti_virus":"security_updates"] = sec_pivot.loc["anti_virus":"security_updates"]/sec_pivot.loc["Total"] * 100



year                2006    2007        2008    
security_software           
anti_virus          38.5    40.579710   38.723404
firewall            32.0    34.299517   34.468085
security_updates    29.5    25.120773   26.808511
Total              200.0    207.000000  235.000000

如果不在索引中,会变得更复杂一些,但不会太多:

sec_pivot.loc[sec_pivot.index != 'Total', 1:] = sec_pivot[sec_pivot.index != 'Total'].iloc[:,1:]/sec_pivot.iloc[:,1:].loc["Total"] * 100

请注意,1: 表示 从第 1 列到结尾 。我考虑你的年份从列索引 1 开始(2006 年)。如果您的 df 中还有其他列,请将 1: 更改为 a:b,其中 a 是第一年列的索引,而 b 是你去年专栏