使用 pandas GroupBy 获取每个组的统计数据(例如计数、平均值等)?
- 2024-11-22 08:47:00
- admin 原创
- 176
问题描述:
我有一个数据框df
,并使用其中的几列来groupby
:
df['col1','col2','col3','col4'].groupby(['col1','col2']).mean()
通过上述方法,我几乎得到了我需要的表格(数据框)。缺少的是包含每组行数的附加列。换句话说,我有平均值,但我还想知道使用了多少个值来获得这些平均值。例如,第一组中有 8 个值,第二组中有 10 个值,依此类推。
简而言之:如何获取数据框的分组统计数据?
解决方案 1:
快速回答:
获取每个组的行数的最简单方法是调用.size()
,它返回Series
:
df.groupby(['col1','col2']).size()
通常您希望将此结果作为DataFrame
(而不是Series
),因此您可以执行以下操作:
df.groupby(['col1', 'col2']).size().reset_index(name='counts')
如果您想了解如何计算每个组的行数和其他统计数据,请继续阅读下文。
详细示例:
考虑以下示例数据框:
In [2]: df
Out[2]:
col1 col2 col3 col4 col5 col6
0 A B 0.20 -0.61 -0.49 1.49
1 A B -1.53 -1.01 -0.39 1.82
2 A B -0.44 0.27 0.72 0.11
3 A B 0.28 -1.32 0.38 0.18
4 C D 0.12 0.59 0.81 0.66
5 C D -0.13 -1.65 -1.64 0.50
6 C D -1.42 -0.11 -0.18 -0.44
7 E F -0.00 1.42 -0.26 1.17
8 E F 0.91 -0.47 1.35 -0.34
9 G H 1.48 -0.63 -1.14 0.17
首先让我们使用它.size()
来获取行数:
In [3]: df.groupby(['col1', 'col2']).size()
Out[3]:
col1 col2
A B 4
C D 3
E F 2
G H 1
dtype: int64
然后让我们使用它.size().reset_index(name='counts')
来获取行数:
In [4]: df.groupby(['col1', 'col2']).size().reset_index(name='counts')
Out[4]:
col1 col2 counts
0 A B 4
1 C D 3
2 E F 2
3 G H 1
包括更多统计结果
当你想要计算分组数据的统计数据时,它通常看起来像这样:
In [5]: (df
...: .groupby(['col1', 'col2'])
...: .agg({
...: 'col3': ['mean', 'count'],
...: 'col4': ['median', 'min', 'count']
...: }))
Out[5]:
col4 col3
median min count mean count
col1 col2
A B -0.810 -1.32 4 -0.372500 4
C D -0.110 -1.65 3 -0.476667 3
E F 0.475 -0.47 2 0.455000 2
G H -0.630 -0.63 1 1.480000 1
由于嵌套的列标签,并且行数是基于每列的,因此上面的结果有点烦人。
为了更好地控制输出,我通常将统计数据拆分为单独的聚合,然后使用 进行组合join
。它看起来像这样:
In [6]: gb = df.groupby(['col1', 'col2'])
...: counts = gb.size().to_frame(name='counts')
...: (counts
...: .join(gb.agg({'col3': 'mean'}).rename(columns={'col3': 'col3_mean'}))
...: .join(gb.agg({'col4': 'median'}).rename(columns={'col4': 'col4_median'}))
...: .join(gb.agg({'col4': 'min'}).rename(columns={'col4': 'col4_min'}))
...: .reset_index()
...: )
...:
Out[6]:
col1 col2 counts col3_mean col4_median col4_min
0 A B 4 -0.372500 -0.810 -1.32
1 C D 3 -0.476667 -0.110 -1.65
2 E F 2 0.455000 0.475 -0.47
3 G H 1 1.480000 -0.630 -0.63
脚注
用于生成测试数据的代码如下所示:
In [1]: import numpy as np
...: import pandas as pd
...:
...: keys = np.array([
...: ['A', 'B'],
...: ['A', 'B'],
...: ['A', 'B'],
...: ['A', 'B'],
...: ['C', 'D'],
...: ['C', 'D'],
...: ['C', 'D'],
...: ['E', 'F'],
...: ['E', 'F'],
...: ['G', 'H']
...: ])
...:
...: df = pd.DataFrame(
...: np.hstack([keys,np.random.randn(10,4).round(2)]),
...: columns = ['col1', 'col2', 'col3', 'col4', 'col5', 'col6']
...: )
...:
...: df[['col3', 'col4', 'col5', 'col6']] = \n ...: df[['col3', 'col4', 'col5', 'col6']].astype(float)
...:
免责声明:
如果您要聚合的某些列具有空值,那么您确实需要将组行计数视为每列的独立聚合。否则,您可能会对实际用于计算平均值等内容的记录数产生误解,因为 pandas 会NaN
在不告知您的情况下删除平均值计算中的条目。
解决方案 2:
在groupby
对象上,该agg
函数可以采用列表来同时应用几种聚合方法。这应该会给你所需的结果:
df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).agg(['mean', 'count'])
解决方案 3:
瑞士军刀:GroupBy.describe
返回每个组的、、count
和其他有用的统计数据。mean
`std`
df.groupby(['A', 'B'])['C'].describe()
count mean std min 25% 50% 75% max
A B
bar one 1.0 0.40 NaN 0.40 0.40 0.40 0.40 0.40
three 1.0 2.24 NaN 2.24 2.24 2.24 2.24 2.24
two 1.0 -0.98 NaN -0.98 -0.98 -0.98 -0.98 -0.98
foo one 2.0 1.36 0.58 0.95 1.15 1.36 1.56 1.76
three 1.0 -0.15 NaN -0.15 -0.15 -0.15 -0.15 -0.15
two 2.0 1.42 0.63 0.98 1.20 1.42 1.65 1.87
要获取特定统计数据,只需选择它们,
df.groupby(['A', 'B'])['C'].describe()[['count', 'mean']]
count mean
A B
bar one 1.0 0.400157
three 1.0 2.240893
two 1.0 -0.977278
foo one 2.0 1.357070
three 1.0 -0.151357
two 2.0 1.423148
注意:如果您只需要计算 1 或 2 个统计数据,那么使用
groupby.agg
并仅计算这些列可能会更快,否则您将执行浪费的计算。
describe
适用于多列(更改['C']
为['C', 'D']
- 或将其完全删除 - 并查看会发生什么,结果是一个多索引列数据框)。
您还可以获得字符串数据的不同统计数据。以下是示例:
df2 = df.assign(D=list('aaabbccc')).sample(n=100, replace=True)
with pd.option_context('precision', 2):
display(df2.groupby(['A', 'B'])
.describe(include='all')
.dropna(how='all', axis=1))
C D
count mean std min 25% 50% 75% max count unique top freq
A B
bar one 14.0 0.40 5.76e-17 0.40 0.40 0.40 0.40 0.40 14 1 a 14
three 14.0 2.24 4.61e-16 2.24 2.24 2.24 2.24 2.24 14 1 b 14
two 9.0 -0.98 0.00e+00 -0.98 -0.98 -0.98 -0.98 -0.98 9 1 c 9
foo one 22.0 1.43 4.10e-01 0.95 0.95 1.76 1.76 1.76 22 2 a 13
three 15.0 -0.15 0.00e+00 -0.15 -0.15 -0.15 -0.15 -0.15 15 1 c 15
two 26.0 1.49 4.48e-01 0.98 0.98 1.87 1.87 1.87 26 2 b 15
欲了解更多信息,请参阅文档。
熊猫> = 1.1:DataFrame.value_counts
如果您只想捕捉每个组的大小,此功能从 pandas 1.1 开始可用,它可以缩短时间GroupBy
并且速度更快。
df.value_counts(subset=['col1', 'col2'])
最小示例
# Setup
np.random.seed(0)
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C' : np.random.randn(8),
'D' : np.random.randn(8)})
df.value_counts(['A', 'B'])
A B
foo two 2
one 2
three 1
bar two 1
three 1
one 1
dtype: int64
其他统计分析工具
如果您在上面没有找到您想要的内容,用户指南中有一个受支持的静态分析、相关性和回归工具的综合列表。
解决方案 4:
要获取多个统计数据、折叠索引并保留列名:
df = df.groupby(['col1','col2']).agg(['mean', 'count'])
df.columns = [ ' '.join(str(i) for i in col) for col in df.columns]
df.reset_index(inplace=True)
df
生成:
解决方案 5:
我们可以使用 groupby 和 count 轻松完成此操作。但是,我们应该记得使用 reset_index()。
df[['col1','col2','col3','col4']].groupby(['col1','col2']).count().\nreset_index()
解决方案 6:
请尝试此代码
new_column=df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).count()
df['count_it']=new_column
df
我认为代码将添加一个名为“count it”的列,用于计数每个组
解决方案 7:
创建一个组对象并调用如下例所示的方法:
grp = df.groupby(['col1', 'col2', 'col3'])
grp.max()
grp.mean()
grp.describe()
解决方案 8:
如果您熟悉 tidyverse R 包,可以使用以下 Python 实现此操作:
from datar.all import tibble, rnorm, f, group_by, summarise, mean, n, rep
df = tibble(
col1=rep(['A', 'B'], 5),
col2=rep(['C', 'D'], each=5),
col3=rnorm(10),
col4=rnorm(10)
)
df >> group_by(f.col1, f.col2) >> summarise(
count=n(),
col3_mean=mean(f.col3),
col4_mean=mean(f.col4)
)
col1 col2 n mean_col3 mean_col4
0 A C 3 -0.516402 0.468454
1 A D 2 -0.248848 0.979655
2 B C 2 0.545518 -0.966536
3 B D 3 -0.349836 -0.915293
[Groups: ['col1'] (n=2)]
我是datar包的作者。如果您在使用过程中遇到任何问题,请随时提交问题。
解决方案 9:
pivot_table
具有特定aggfunc
的
对于聚合统计数据的数据框,pivot_table
也可以使用。它生成的表格与 Excel 数据透视表并无太大区别。基本思想是将要聚合的列作为 传入values=
,将分组列作为 传入index=
,并将聚合器函数作为 传入aggfunc=
(所有可接受的优化函数都groupby.agg
可以)。
一个优点pivot_table
是groupby.agg
,对于多列,它会生成一个size
列,而为每一列groupby.agg
创建一个size
列(除一列之外的所有列都是多余的)。
agg_df = df.pivot_table(
values=['col3', 'col4', 'col5'],
index=['col1', 'col2'],
aggfunc=['size', 'mean', 'median']
).reset_index()
# flatten the MultiIndex column (should be omitted if MultiIndex is preferred)
agg_df.columns = [i if not j else f"{j}_{i}" for i,j in agg_df.columns]
使用命名聚合来自定义列名
对于自定义列名,rename
从一开始就使用命名聚合,而不是多次调用。
来自文档:
为了支持特定于列的聚合并控制输出列名称,pandas 接受 GroupBy.agg() 中的特殊语法,称为“命名聚合”,其中
关键字是输出列名称
这些值是元组,其第一个元素是要选择的列,第二个元素是要应用于该列的聚合。pandas 提供了带有字段 ['column', 'aggfunc'] 的 pandas.NamedAgg 命名元组,以使参数更清晰。与往常一样,聚合可以是可调用的或字符串别名。
例如,要生成聚合数据框,其中col3
、col4
和中的每个都col5
计算其平均值和计数,可以使用以下代码。请注意,它将重命名列步骤作为 的一部分执行groupby.agg
。
aggfuncs = {f'{c}_{f}': (c, f) for c in ['col3', 'col4', 'col5'] for f in ['mean', 'count']}
agg_df = df.groupby(['col1', 'col2'], as_index=False).agg(**aggfuncs)
命名聚合的另一个用例是如果每列都需要不同的聚合器函数。例如,如果只需要的平均值col3
、的中位数col4
和min
的col5
,并且具有自定义列名,则可以使用以下代码完成。
agg_df = df.groupby(['col1', 'col2'], as_index=False).agg(col3_mean=('col3', 'mean'), col4_median=('col4', 'median'), col5_min=('col5', 'min'))
# or equivalently,
agg_df = df.groupby(['col1', 'col2'], as_index=False).agg(**{'_'.join(p): p for p in [('col3', 'mean'), ('col4', 'median'), ('col5', 'min')]})
解决方案 10:
df_group = (df.groupby(['city','gender'])[['age',"grade"]]
.agg([('average','mean'),('freq','count')])
.reset_index())
城市和性别是群组列。
年龄和年级是依赖列(我根据它们计算平均值)。
平均值列的名称将是平均值,计数列的名称将是频率
解决方案 11:
“命名聚合”支持 SQL 样式的聚合函数,以as_index=False
获取分组列:
animals.groupby("kind", as_index=False).agg(
min_height=("height", "min"),
max_height=("height", "max"),
average_weight=("weight", "mean"),
)
这将使用列名和函数名作为字符串。SQL 等效代码为
SELECT
MIN(height) AS min_height,
MAX(height) AS max_height,
AVG(height) AS average_weight
FROM animals
GROUP BY kind
常见聚合函数文档(count、max、min、first 等)
解决方案 12:
另一种选择:
import pandas as pd
import numpy as np
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C' : np.random.randn(8),
'D' : np.random.randn(8)})
df
A B C D
0 foo one 0.808197 2.057923
1 bar one 0.330835 -0.815545
2 foo two -1.664960 -2.372025
3 bar three 0.034224 0.825633
4 foo two 1.131271 -0.984838
5 bar two 2.961694 -1.122788
6 foo one -0.054695 0.503555
7 foo three 0.018052 -0.746912
pd.crosstab(df.A, df.B).stack().reset_index(name='count')
输出:
A B count
0 bar one 1
1 bar three 1
2 bar two 1
3 foo one 2
4 foo three 1
5 foo two 2