Python Pandas 数据框:如何将 describe() 应用于每个组并添加到新列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33575587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:35:33  来源:igfitidea点击:

Pandas dataframe: how to apply describe() to each group and add to new columns?

pythonnumpypandasdataframe

提问by Robin1988

df:

df:

name score
A      1
A      2
A      3
A      4
A      5
B      2
B      4
B      6 
B      8

Want to get the following new dataframe in the form of below:

想要以下面的形式获得以下新数据框:

   name count mean std min 25% 50% 75% max
    A     5    3    .. ..  ..  ..  ..  ..
    B     4    5    .. ..  ..  ..  ..  ..

How to exctract the information from df.describe() and reformat it? Thanks

如何从 df.describe() 中提取信息并重新格式化?谢谢

采纳答案by Pedro M Duarte

Define some data

定义一些数据

In[1]:
import pandas as pd
import io

data = """
name score
A      1
A      2
A      3
A      4
A      5
B      2
B      4
B      6
B      8
    """

df = pd.read_csv(io.StringIO(data), delimiter='\s+')
print(df)

.

.

Out[1]:
  name  score
0    A      1
1    A      2
2    A      3
3    A      4
4    A      5
5    B      2
6    B      4
7    B      6
8    B      8

Solution

解决方案

A nice approach to this problem uses a generator expression (see footnote) to allow pd.DataFrame()to iterate over the results of groupby, and construct the summary stats dataframe on the fly:

解决这个问题的一个很好的方法是使用生成器表达式(参见脚注)pd.DataFrame()来迭代 的结果groupby,并动态构建汇总统计数据框:

In[2]:
df2 = pd.DataFrame(group.describe().rename(columns={'score':name}).squeeze()
                         for name, group in df.groupby('name'))

print(df2)

.

.

Out[2]:
   count  mean       std  min  25%  50%  75%  max
A      5     3  1.581139    1  2.0    3  4.0    5
B      4     5  2.581989    2  3.5    5  6.5    8

Here the squeezefunction is squeezing out a dimension, to convert the one-column group summary stats Dataframeinto a Series.

这里的squeeze函数是挤压一个维度,将一列组汇总统计信息Dataframe转换为Series.

Footnote: A generator expression has the form my_function(a) for a in iterator, or if iteratorgives us back two-element tuples, as in the case of groupby: my_function(a,b) for a,b in iterator

脚注:生成器表达式的形式为my_function(a) for a in iterator,或者 ifiterator返回两个元素的tuples,如 的情况groupbymy_function(a,b) for a,b in iterator

回答by Leb

import pandas as pd
import io
import numpy as np

data = """
name score
A      1
A      2
A      3
A      4
A      5
B      2
B      4
B      6
B      8
    """

df = pd.read_csv(io.StringIO(data), delimiter='\s+')

df2 = df.groupby('name').describe().reset_index().T.drop('name')
arr = np.array(df2).reshape((4,8))

df2 = pd.DataFrame(arr[1:], index=['name','A','B'])

print(df2)

That will give you df2 as:

这会给你 df2 为:

              0     1        2    3    4    5    6    7
    name  count  mean      std  min  25%  50%  75%  max
    A         5     3  1.58114    1    2    3    4    5
    B         4     5  2.58199    2  3.5    5  6.5    8

回答by SirParselot

Well I managed to get what you wanted but it doesn't scale very well.

好吧,我设法得到了你想要的东西,但它的伸缩性不是很好。

import pandas as pd

name = ['a','a','a','a','a','b','b','b','b','b']
score = [1,2,3,4,5,2,4,6,8]

d = pd.DataFrame(zip(name,score), columns=['Name','Score'])
d = d.groupby('Name').describe()
d = d.reset_index()
df2 = pd.DataFrame(zip(d.level_1[8:], list(d.Score)[:8], list(d.Score)[8:]), columns = ['Name','A','B']).T

print df2

          0     1         2    3    4    5    6    7
Name  count  mean       std  min  25%  50%  75%  max
A         5     3  1.581139    1    2    3    4    5
B         4     5  2.581989    2  3.5    5  6.5    8

回答by CT Zhu

Nothing beats one-liner:

没有什么能比得上单线:

In [145]:

print df.groupby('name').describe().reset_index().pivot(index='name', values='score', columns='level_1')

level_1  25%  50%  75%  count  max  mean  min       std
name                                                   
A        2.0    3  4.0      5    5     3    1  1.581139
B        3.5    5  6.5      4    8     5    2  2.581989

回答by Andrey Vykhodtsev

there is even a shorter one :)

还有一个更短的:)

print df.groupby('name').describe().unstack(1)

Nothing beats one-liner:

In [145]:

print df.groupby('name').describe().reset_index().pivot(index='name', values='score', columns='level_1')

没有什么能比得上单线:

在 [145] 中:

打印 df.groupby('name').describe().reset_index().pivot(index='name', values='score', columns='level_1')

回答by Abhishek Singla

Table is stored in dataframe named df

表存储在名为 df

df= pd.read_csv(io.StringIO(data),delimiter='\s+')

Just specify column name and describegive you required output. In this way you calculate w.r.t any column

只需指定列名并describe为您提供所需的输出。通过这种方式,您可以计算任何列

df.groupby('name')['score'].describe()