Skip to main content
 首页 » 编程设计

python之使用函数在每列中获取均值/中值/众数/四分位数/分位数

2024年12月31日15yjmyzz

我是 jupyter notebook 的新手,想知道如何在函数内获取列的分位数:

数据框:

num_likes | num_post | ... |  
464.0     | 142.0    | ... | 
364.0     | 125.0    | ... | 
487.0     | 106.0    | ... | 
258.0     | 123.0    | ... | 
125.0     | 103.0    | ... | 

我的函数:

def myFunction(x): 
    q22 = dataframe["num_likes"].quantile(0.22) 
    q45 = dataframe["num_likes"].quantile(0.45) 
    qc = q45 - q22 
    k = 3 
 
    if x >= q45 + k * qc: 
        return q45 + k * qc 
    elif x <= q22 - k * qc: 
        return q22 - k * qc 

现在,由于我不知道如何获取它,所以我最终为我拥有的每一列运行了该函数。另外,我尝试运行它,但似乎无法正常工作

data["num_likes"].apply(lambda x : myFunction(x))[:5] 

此外,结果似乎是错误的,因为我没有看到任何返回

    num_likes | num_post | ... |  
    NaN       | None     | ... | 
    NaN       | None     | ... | 
    NaN       | None     | ... | 
    NaN       | None     | ... | 
    NaN       | None     | ... | 

请您参考如下方法:

你得到 None 的原因是因为你的 if-elseif block 没有路径返回 true 所以 myFunction 正在返回 无。您是说 if-else 吗?

除此之外,为了清理您拥有的东西,我会做一些不同的事情。首先q22、q45和qc只需要计算一次(根据上面的逻辑),这些可以传入函数中,而不是每次都在函数中计算。其次,在这种情况下您不需要创建 lambda,apply ( docs ) 接受一个 python 可调用对象(您的函数),并且可以传递如下所示的其他参数。

df = pd.DataFrame({ 
    'num_likes': [464.0, 364.0, 487.0, 258.0, 125.0], 
    'num_post': [142.0, 125.0, 106.0, 123.0, 103.0] 
}) 
 
def myFunction(x, q22, q45, qc): 
    k = 3 
 
    if x >= q45 + k * qc: 
        return q45 + k * qc 
    elif x <= q22 - k * qc: 
        return q22 - k * qc 
    else: 
        return -1 
 
q22 = df["num_likes"].quantile(0.22) 
q45 = df["num_likes"].quantile(0.45) 
qc = q45 - q22 
 
# pass additional arguments in an tuple, they will be passed to myFunction 
df.num_likes.apply(myFunction, args=(q22, q45, qc)) 
 
# this will return a series which can be assigned to new column 
# 0   -1 
# 1   -1 
# 2   -1 
# 3   -1 
# 4   -1 
# Name: num_likes, dtype: int64