我需要按服务器名称统计使用百分比的出现次数。我有这个数据框。
df
Server Bandwidth 1-Jun 6-June 12-Jun 1-Jul
ServerA 10000 5000 6000 7500 8000
ServerB 100000 60000 80000 75000 80000
ServerC 20000 5000 6000 7500 8000
ServerD 30000 5000 6000 7500 8000
ServerF 10000 5000 6000 7500 8000
ServerX 5000 5000 6000 7500 8000
第一。我需要计算给定带宽的每月使用百分比。
cols=df.columns(difference(['Server','Bandwidth'], sort=false
out=df[cols].div(df['Bandwidth'], axis=0, combine_first(df)[list(df)]
我得到这个输出:
out
Server Bandwidth 1-Jun 6-June 12-Jun 1-Jul
ServerA 10000 0.50 0.60 0.75 0.80
ServerB 100000 0.60 0.80 0.75 0.80
ServerC 20000 0.25 0.30 0.38 0.40
等等
接下来,我需要将使用百分比数据放入箱中,70%-80%、80%-90%、90%-100%、100%+
结果数据框需要是这样的:
result_df
Server Bandwidth 70%-80% 80%-90% 90%-100% 100%+
ServerA 10000 1 1 0 0
ServerB 100000 1 2 0 0
ServerC 20000 0 0 0 0
等等
如何统计pandas中服务器分组出现的百分比?
我使用 unstack 重塑:
ndf = df.set_index(['Server', 'Bandwidth']).stack() \
.reset_index().rename(columns={'level_2': 'date', 0: 'usage'})
然后创建类别:
ndf['utilisation'] = ndf['usage'] / ndf['Bandwidth']
ndf['cat'] = pd.cut(ndf['utilisation'] * 100, [70, 80, 90, 99, 100], right=False)
然后我对服务器和类别进行聚合,计算单个列(使用哪个特定列实际上并不重要)。
>>> ndf.groupby(['Server', 'cat'])['utilisation'].count().unstack()
cat [70, 80) [80, 90) [90, 99) [99, 100)
Server
ServerA 1 1 0 0
ServerB 1 2 0 0
ServerC 0 0 0 0
ServerD 0 0 0 0
ServerF 1 1 0 0
ServerX 0 0 0 0