Python 将统计信息从百分比更改为事件数
我发现了一个有趣的库,我想对这段代码进行修改。我希望看到事件数除以事件总数(如5/52等),以百分比表示。我如何添加它 链接到图书馆: 这部分代码显示数据,但我不知道如何更改:Python 将统计信息从百分比更改为事件数,python,Python,我发现了一个有趣的库,我想对这段代码进行修改。我希望看到事件数除以事件总数(如5/52等),以百分比表示。我如何添加它 链接到图书馆: 这部分代码显示数据,但我不知道如何更改: total = np.array([bs['statistic'].sum() for bs in bin_statistic]).sum() # replace raw counts with percentages and add percentage sign (note immutable named
total = np.array([bs['statistic'].sum() for bs in bin_statistic]).sum()
# replace raw counts with percentages and add percentage sign (note immutable named tuple so used _replace)
for bs in bin_statistic:
bs['statistic'] = (pd.DataFrame(bs['statistic'] / total)
.applymap(lambda x: '{:.0%}'.format(x))
.values)
您显示的代码将数据框的
“statistic”
列替换为包含百分比的新列
bs['statistic'] = (pd.DataFrame(bs['statistic'] / total)
.applymap(lambda x: '{:.0%}'.format(x))
.values)
让我们把它分成几行,以便更容易理解:
# divide the statistic column by the total
percentages = pd.DataFrame(bs['statistic'] / total)
# format percentages using the specifier {:.0%}
bs['statistic'] = (percentages.applymap(lambda x: '{:.0%}'.format(x)).values)
计算百分比后,使用str.format()
函数将每个值格式化为小数点后零位的百分比()
所以你需要做的就是改变格式化的内容,以及格式化的方式
outputval = pd.DataFrame(bs['statistic']) # it might not be necessary to cast to pd.DataFrame
bs['statistic'] = (outputval.applymap(lambda x: '{0:.0f}/{1:.0f}'.format(x, total)).values)
或者在一行中:
bs['statistic'] = (pd.DataFrame(bs['statistic']).applymap(lambda x: '{0:.0f}/{1:.0f}'.format(x, total)).values)
(pd.DataFrame(bs['statistic']).applymap(lambda x:'{0}/{1}'。格式(x,total)).values)
@PranavHosangadi谢谢,它的作品。但现在我看到了一些奇怪的数字(照片将在上面的帖子中发送),这是因为这些数字可能是浮动的。您可以将:.0f
添加到格式说明符中,告诉它写入零位小数。下面是我的答案,我写得很糟糕。我不是指格式。例如,其中一个扇区中有3个点,计为2,这些点的总和为4,但应为11。对不起。它起作用了,是我的错。谢谢你的帮助。我犯了个大错,没看见他。