【问题标题】:Getting a Mean/Median/Mode/Quartile/Quantile in each column using a function使用函数在每列中获取平均值/中位数/众数/四分位数/分位数
【发布时间】:2019-02-26 22:52:21
【问题描述】:

我是 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     | ... |

【问题讨论】:

    标签: python python-3.x pandas jupyter-notebook


    【解决方案1】:

    你得到None的原因是因为你的if-elseif块的路径没有返回true所以myFunction返回None。你的意思是if-else

    除此之外,为了清理你拥有的东西,我会做一些不同的事情。首先 q22、q45 和 qc 只需要计算一次(基于上面的逻辑),这些可以传递到函数中,而不是每次在函数中计算。其次,在这种情况下,您不需要创建 lambdaapply (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
    

    【讨论】:

    • 很抱歉,我在发布之前忘记先检查分位数的范围,因此想知道为什么我无法得到我想要的结果。我现在可以理解 myFunction 中的缺陷了,感谢您指出一切。我只是有一个问题,函数是如何理解“x”是用于列中的每个元素的,并在 myFunction 中传递它?
    • 这是因为my_series.apply(myFunc)for item in series: myFunc(item) 的逻辑等价物,默认情况下它将迭代传递系列中所有项目的下一个项目。同样,如果您执行 df.groupby('num_likes').apply(myFunc) 之类的操作,则传递给 myFunc 的第一个参数是一个数据框(按 groupby 分组的那个)
    猜你喜欢
    • 1970-01-01
    • 2011-10-23
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多