简体   繁体   English

Pandas pivot_table百分位数

[英]Pandas pivot_table percentile

I'm trying to describe columns A, B by mean, median, 25th percentile, 75th percentile, standard deviation. 我试图通过平均值,中位数,第25百分位数,第75百分位数,标准差来描述A列,B列。

df = pd.DataFrame({'A':[1,9,3,4,6,8,2,7],
                   'B':[2,4,7,8,9,2,5,6],
                   'S':['L','L','L','S','L','S','S','L']})

Here is what I did and it worked since I only have 25th percentile: 这是我做的,它起作用,因为我只有25%的百分位数:

df.pivot_table(columns = ['S'], values = ['A','B'], aggfunc = [np.mean, lambda x: np.percentile(x,25), np.median, np.std])

But if I also put the 75th percentile in, it gives me the error message: 但如果我也把第75百分位数,它给我错误信息:

Reindexing only valid with uniquely valued Index objects

Ideally I would like the output list the 75th percentile in the next columns. 理想情况下,我希望输出列表在下一列中达到第75个百分点。

This will do what I think you want, but without a lambda and few extra lines: 这将做我认为你想要的,但没有lambda和额外的几行:

def my25(g):
    return np.percentile(g, 25)

def my75(g):
    return np.percentile(g, 75)

df.pivot_table(columns = ['S'], values = ['A','B'], 
               aggfunc = [np.mean, my25, np.median, np.std, my75])

        mean      my25    median         std      my75     
S    L     S    L    S      L  S     L     S    L    S
A  5.2  4.67    3  3.0      6  4  3.19  3.06    7  6.0
B  5.6  5.00    4  3.5      6  5  2.70  3.00    7  6.5

EDIT: actually, it is possible to use only lambda functions if you use groupby to aggregate instead of pivot_table, and supply a name to each function. 编辑:实际上,如果使用groupby聚合而不是pivot_table,则可以仅使用lambda函数,并为每个函数提供名称。

func_lst = [('mean',np.mean), ('25',lambda x:np.percentile(x,0.25)), 
            ('med',np.median), ('std',np.std), ('75',lambda x:np.percentile(x,0.75))]

df.groupby('S').agg(func_lst).stack(level=0).unstack(level=0).swaplevel(0,1,axis=1) df.groupby( 'S')。AGG(func_lst).STACK(级别= 0).unstack(级别= 0).swaplevel(0,1,轴= 1)

        mean      25    med         std      75     
S    L     S  L    S   L  S     L     S  L    S
A  5.2  4.67  3  3.0   6  4  3.19  3.06  7  6.0
B  5.6  5.00  4  3.5   6  5  2.70  3.00  7  6.5

I thought using func_lst in a pivot_table call might work but it doesn't. 我认为在pivot_table调用中使用func_lst可能有效,但事实并非如此。 Anyway to me it is clearer to just define the my25, my75 functions and use the pivot_table. 无论如何,只需定义my25,my75函数并使用pivot_table就更清楚了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM