Python 熊猫中布尔级数的百分比函数

Python 熊猫中布尔级数的百分比函数,python,pandas,Python,Pandas,使用与此类似的函数: def percentage(part, whole): return 100 * float(part)/float(whole) 我可以得到调用函数的百分比: percentage(215,413) 但是我怎样才能得到布尔级数的真与假的百分比呢 s = pd.Series(np.random.randn(5) +5) s > 5 0 True 1 False 2 False 3 True 4 True dtype

使用与此类似的函数:

def percentage(part, whole):
    return 100 * float(part)/float(whole)
我可以得到调用函数的百分比:

percentage(215,413)
但是我怎样才能得到布尔级数的真与假的百分比呢

s = pd.Series(np.random.randn(5) +5)

s > 5

0     True
1    False
2    False
3     True
4     True
dtype: bool

期望输出是序列中真实值的百分比(在上面的示例中为60%)。我是否需要映射一个函数来获得输出?请告诉我最好的方法。谢谢

只需计算布尔级数的平均值。由于True映射为1,False映射为0,因此只需计算平均值即可得到百分比:

import pandas as pd, numpy as np
s = pd.Series(np.random.randn(5) +5)
(s > 5).mean()
0.59999999999999998

内置串联运算符是另一种方便的方法:

s.gt(5).mean()
使用
(s>5.sum()
?(s>5.sum()/len)。然后是1-(s>5).sum()/len(s)