分组依据:split-apply-combine#
“分组依据”是指包含以下一个或多个步骤的过程
拆分数据,根据某些标准将其分成组。
应用一个函数到每个组,独立进行。
组合结果到一个数据结构中。
其中,拆分步骤是最直接的。在应用步骤中,我们可能希望执行以下操作之一
聚合:为每个组计算一个(或多个)摘要统计量。一些例子
计算组的和或均值。
计算组的大小/计数。
转换:执行一些特定于组的计算,并返回一个具有相同索引的对象。一些例子
标准化组内数据(z-score)。
使用每个组派生的值填充组内的 NA。
过滤:根据一个计算结果为 True 或 False 的组级计算,丢弃某些组。一些例子
丢弃属于成员很少的组的数据。
基于组的和或均值过滤掉数据。
许多这些操作都定义在 GroupBy 对象上。这些操作类似于 聚合 API、窗口 API 和 重采样 API。
可能存在某个操作不属于以上任何一类,或者是一些组合。在这种情况下,可以使用 GroupBy 的 apply 方法来计算该操作。如果该操作不属于以上三类,该方法将检查应用步骤的结果,并尝试将其合理地组合成一个单一结果。
注意
使用内置的 GroupBy 操作将操作拆分成多个步骤,将比使用带用户定义 Python 函数的 apply 方法更有效。
对于使用过 SQL 工具(或 itertools)的人来说,“GroupBy”这个名称应该很熟悉,在这些工具中你可以写出类似的代码
SELECT Column1, Column2, mean(Column3), sum(Column4)
FROM SomeTable
GROUP BY Column1, Column2
我们的目标是让 pandas 能够自然轻松地表达此类操作。我们将分别介绍 GroupBy 功能的各个方面,然后提供一些非平凡的例子/用例。
有关一些高级策略,请参阅 cookbook。
拆分对象为组#
分组的抽象定义是提供标签到组名的映射。要创建一个 GroupBy 对象(稍后将详细介绍 GroupBy 对象是什么),你可以这样做
In [1]: speeds = pd.DataFrame(
...: [
...: ("bird", "Falconiformes", 389.0),
...: ("bird", "Psittaciformes", 24.0),
...: ("mammal", "Carnivora", 80.2),
...: ("mammal", "Primates", np.nan),
...: ("mammal", "Carnivora", 58),
...: ],
...: index=["falcon", "parrot", "lion", "monkey", "leopard"],
...: columns=("class", "order", "max_speed"),
...: )
...:
In [2]: speeds
Out[2]:
class order max_speed
falcon bird Falconiformes 389.0
parrot bird Psittaciformes 24.0
lion mammal Carnivora 80.2
monkey mammal Primates NaN
leopard mammal Carnivora 58.0
In [3]: grouped = speeds.groupby("class")
In [4]: grouped = speeds.groupby(["class", "order"])
映射可以通过多种方式指定
一个 Python 函数,将对每个索引标签调用。
一个与索引长度相同的列表或 NumPy 数组。
一个 dict 或
Series,提供一个label -> group name映射。对于
DataFrame对象,一个字符串,指示要用于分组的列名或索引级别名称。以上任何一种的列表。
我们将这些分组对象统称为键。例如,考虑以下 DataFrame
注意
传递给 groupby 的字符串可以引用列名或索引级别。如果一个字符串同时匹配列名和索引级别名称,则会引发 ValueError。
In [5]: 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),
...: }
...: )
...:
In [6]: df
Out[6]:
A B C D
0 foo one 0.469112 -0.861849
1 bar one -0.282863 -2.104569
2 foo two -1.509059 -0.494929
3 bar three -1.135632 1.071804
4 foo two 1.212112 0.721555
5 bar two -0.173215 -0.706771
6 foo one 0.119209 -1.039575
7 foo three -1.044236 0.271860
在 DataFrame 上,我们通过调用 groupby() 来获得一个 GroupBy 对象。此方法返回一个 pandas.api.typing.DataFrameGroupBy 实例。我们可以自然地按 A 或 B 列,或两者同时分组
In [7]: grouped = df.groupby("A")
In [8]: grouped = df.groupby("B")
In [9]: grouped = df.groupby(["A", "B"])
注意
df.groupby('A') 只是 df.groupby(df['A']) 的语法糖。
DataFrame 的 groupby 始终沿轴 0(行)进行操作。要按列拆分,请先进行转置
In [10]: def get_letter_type(letter):
....: if letter.lower() in 'aeiou':
....: return 'vowel'
....: else:
....: return 'consonant'
....:
In [11]: grouped = df.T.groupby(get_letter_type)
pandas 的 Index 对象支持重复值。如果在 groupby 操作中使用了非唯一索引作为分组键,则具有相同索引值的所有值将被视为一个组,因此聚合函数的输出将只包含唯一的索引值。
In [12]: index = [1, 2, 3, 1, 2, 3]
In [13]: s = pd.Series([1, 2, 3, 10, 20, 30], index=index)
In [14]: s
Out[14]:
1 1
2 2
3 3
1 10
2 20
3 30
dtype: int64
In [15]: grouped = s.groupby(level=0)
In [16]: grouped.first()
Out[16]:
1 1
2 2
3 3
dtype: int64
In [17]: grouped.last()
Out[17]:
1 10
2 20
3 30
dtype: int64
In [18]: grouped.sum()
Out[18]:
1 11
2 22
3 33
dtype: int64
请注意,在需要之前不会发生拆分。创建 GroupBy 对象只是验证你是否传递了有效的映射。
注意
许多复杂的各种数据操作都可以用 GroupBy 操作来表示(尽管不能保证是最有效的实现)。你可以非常有创意地使用标签映射函数。
GroupBy 排序#
默认情况下,组键在 groupby 操作期间被排序。但是,你可以传递 sort=False 以获得潜在的速度提升。使用 sort=False 时,组键之间的顺序遵循它们在原始 DataFrame 中出现的顺序。
In [19]: df2 = pd.DataFrame({"X": ["B", "B", "A", "A"], "Y": [1, 2, 3, 4]})
In [20]: df2.groupby(["X"]).sum()
Out[20]:
Y
X
A 7
B 3
In [21]: df2.groupby(["X"], sort=False).sum()
Out[21]:
Y
X
B 3
A 7
请注意,groupby 将保留观测值在每个组内部排序的顺序。例如,下面由 groupby() 创建的组的顺序与它们在原始 DataFrame 中出现的顺序一致。
In [22]: df3 = pd.DataFrame({"X": ["A", "B", "A", "B"], "Y": [1, 4, 3, 2]})
In [23]: df3.groupby("X").get_group("A")
Out[23]:
X Y
0 A 1
2 A 3
In [24]: df3.groupby(["X"]).get_group(("B",))
Out[24]:
X Y
1 B 4
3 B 2
GroupBy 忽略 NA 值#
默认情况下,在 groupby 操作期间,NA 值会被排除在组键之外。但是,如果你想在组键中包含 NA 值,可以通过传递 dropna=False 来实现。
In [25]: df_list = [[1, 2, 3], [1, None, 4], [2, 1, 3], [1, 2, 2]]
In [26]: df_dropna = pd.DataFrame(df_list, columns=["a", "b", "c"])
In [27]: df_dropna
Out[27]:
a b c
0 1 2.0 3
1 1 NaN 4
2 2 1.0 3
3 1 2.0 2
# Default ``dropna`` is set to True, which will exclude NaNs in keys
In [28]: df_dropna.groupby(by=["b"], dropna=True).sum()
Out[28]:
a c
b
1.0 2 3
2.0 2 5
# In order to allow NaN in keys, set ``dropna`` to False
In [29]: df_dropna.groupby(by=["b"], dropna=False).sum()
Out[29]:
a c
b
1.0 2 3
2.0 2 5
NaN 1 4
dropna 参数的默认设置为 True,这意味着 NA 不包含在组键中。
GroupBy 对象属性#
GroupBy 对象的 groups 属性是一个字典,它将每个唯一的组键映射到属于该组的索引标签。在上面的例子中
In [30]: df.groupby("A").groups
Out[30]: {'bar': [1, 3, 5], 'foo': [0, 2, 4, 6, 7]}
In [31]: df.T.groupby(get_letter_type).groups
Out[31]: {'consonant': ['B', 'C', 'D'], 'vowel': ['A']}
在 GroupBy 对象上调用标准的 Python len 函数会返回组的数量,这与 groups 字典的长度相同。
In [32]: grouped = df.groupby(["A", "B"])
In [33]: grouped.groups
Out[33]:
{('bar', 'one'): RangeIndex(start=1, stop=2, step=1),
('bar', 'three'): RangeIndex(start=3, stop=4, step=1),
('bar', 'two'): RangeIndex(start=5, stop=6, step=1),
('foo', 'one'): RangeIndex(start=0, stop=12, step=6),
('foo', 'three'): RangeIndex(start=7, stop=8, step=1),
('foo', 'two'): RangeIndex(start=2, stop=6, step=2)}
In [34]: len(grouped)
Out[34]: 6
GroupBy 将自动完成列名、GroupBy 操作和其他属性。
In [35]: n = 10
In [36]: weight = np.random.normal(166, 20, size=n)
In [37]: height = np.random.normal(60, 10, size=n)
In [38]: time = pd.date_range("1/1/2000", periods=n)
In [39]: gender = np.random.choice(["male", "female"], size=n)
In [40]: df = pd.DataFrame(
....: {"height": height, "weight": weight, "gender": gender}, index=time
....: )
....:
In [41]: df
Out[41]:
height weight gender
2000-01-01 42.849980 157.500553 male
2000-01-02 49.607315 177.340407 male
2000-01-03 56.293531 171.524640 male
2000-01-04 48.421077 144.251986 female
2000-01-05 46.556882 152.526206 male
2000-01-06 68.448851 168.272968 female
2000-01-07 70.757698 136.431469 male
2000-01-08 58.909500 176.499753 female
2000-01-09 76.435631 174.094104 female
2000-01-10 45.306120 177.540920 male
In [42]: gb = df.groupby("gender")
In [43]: gb.<TAB> # noqa: E225, E999
gb.agg gb.boxplot gb.cummin gb.describe gb.filter gb.get_group gb.height gb.last gb.median gb.ngroups gb.plot gb.rank gb.std gb.transform
gb.aggregate gb.count gb.cumprod gb.dtype gb.first gb.groups gb.hist gb.max gb.min gb.nth gb.prod gb.resample gb.sum gb.var
gb.apply gb.cummax gb.cumsum gb.gender gb.head gb.indices gb.mean gb.name gb.ohlc gb.quantile gb.size gb.tail gb.weight
带 MultiIndex 的 GroupBy#
对于分层索引数据,按层次结构中的一个级别进行分组是很自然的。
让我们创建一个具有两级 MultiIndex 的 Series。
In [44]: arrays = [
....: ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
....: ["one", "two", "one", "two", "one", "two", "one", "two"],
....: ]
....:
In [45]: index = pd.MultiIndex.from_arrays(arrays, names=["first", "second"])
In [46]: s = pd.Series(np.random.randn(8), index=index)
In [47]: s
Out[47]:
first second
bar one -0.919854
two -0.042379
baz one 1.247642
two -0.009920
foo one 0.290213
two 0.495767
qux one 0.362949
two 1.548106
dtype: float64
然后我们可以按 s 中的一个级别进行分组。
In [48]: grouped = s.groupby(level=0)
In [49]: grouped.sum()
Out[49]:
first
bar -0.962232
baz 1.237723
foo 0.785980
qux 1.911055
dtype: float64
如果 MultiIndex 指定了名称,则可以传递这些名称而不是级别编号。
In [50]: s.groupby(level="second").sum()
Out[50]:
second
one 0.980950
two 1.991575
dtype: float64
支持按多个级别分组。
In [51]: arrays = [
....: ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
....: ["doo", "doo", "bee", "bee", "bop", "bop", "bop", "bop"],
....: ["one", "two", "one", "two", "one", "two", "one", "two"],
....: ]
....:
In [52]: index = pd.MultiIndex.from_arrays(arrays, names=["first", "second", "third"])
In [53]: s = pd.Series(np.random.randn(8), index=index)
In [54]: s
Out[54]:
first second third
bar doo one -1.131345
two -0.089329
baz bee one 0.337863
two -0.945867
foo bop one -0.932132
two 1.956030
qux bop one 0.017587
two -0.016692
dtype: float64
In [55]: s.groupby(level=["first", "second"]).sum()
Out[55]:
first second
bar doo -1.220674
baz bee -0.608004
foo bop 1.023898
qux bop 0.000895
dtype: float64
索引级别名称可以作为键提供。
In [56]: s.groupby(["first", "second"]).sum()
Out[56]:
first second
bar doo -1.220674
baz bee -0.608004
foo bop 1.023898
qux bop 0.000895
dtype: float64
稍后将介绍 sum 函数和聚合。
使用索引级别和列对 DataFrame 进行分组#
DataFrame 可以通过列和索引级别的组合进行分组。你可以指定列名和索引名,或者使用 Grouper。
我们先创建一个带有 MultiIndex 的 DataFrame。
In [57]: arrays = [
....: ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
....: ["one", "two", "one", "two", "one", "two", "one", "two"],
....: ]
....:
In [58]: index = pd.MultiIndex.from_arrays(arrays, names=["first", "second"])
In [59]: df = pd.DataFrame({"A": [1, 1, 1, 1, 2, 2, 3, 3], "B": np.arange(8)}, index=index)
In [60]: df
Out[60]:
A B
first second
bar one 1 0
two 1 1
baz one 1 2
two 1 3
foo one 2 4
two 2 5
qux one 3 6
two 3 7
然后我们按 second 索引级别和 A 列对 df 进行分组。
In [61]: df.groupby([pd.Grouper(level=1), "A"]).sum()
Out[61]:
B
second A
one 1 2
2 4
3 6
two 1 4
2 5
3 7
索引级别也可以按名称指定。
In [62]: df.groupby([pd.Grouper(level="second"), "A"]).sum()
Out[62]:
B
second A
one 1 2
2 4
3 6
two 1 4
2 5
3 7
索引级别名称可以直接作为键传递给 groupby。
In [63]: df.groupby(["second", "A"]).sum()
Out[63]:
B
second A
one 1 2
2 4
3 6
two 1 4
2 5
3 7
GroupBy 中的 DataFrame 列选择#
一旦你从 DataFrame 创建了 GroupBy 对象,你可能想对每个列做不同的事情。因此,通过在 GroupBy 对象上使用 [],就像从 DataFrame 中获取列一样,你可以这样做
In [64]: 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),
....: }
....: )
....:
In [65]: df
Out[65]:
A B C D
0 foo one -0.575247 1.346061
1 bar one 0.254161 1.511763
2 foo two -1.143704 1.627081
3 bar three 0.215897 -0.990582
4 foo two 1.193555 -0.441652
5 bar two -0.077118 1.211526
6 foo one -0.408530 0.268520
7 foo three -0.862495 0.024580
In [66]: grouped = df.groupby(["A"])
In [67]: grouped_C = grouped["C"]
In [68]: grouped_D = grouped["D"]
这主要是对另一种更冗长的方法的语法糖。
In [69]: df["C"].groupby(df["A"])
Out[69]: <pandas.api.typing.SeriesGroupBy object at 0x7fc1273204d0>
此外,这种方法避免了重新计算从传递的键派生的内部分组信息。
如果你想对分组列进行操作,也可以包含它们。
In [70]: grouped[["A", "B"]].sum()
Out[70]:
A B
A
bar barbarbar onethreetwo
foo foofoofoofoofoo onetwotwoonethree
注意
pandas 的 groupby 操作在操作后会丢弃列 Index 对象的 name 字段。此更改确保了在 groupby 操作中不同列选择方法之间的语法一致性。
遍历组#
有了 GroupBy 对象,遍历分组数据非常自然,并且与 itertools.groupby() 类似。
In [71]: grouped = df.groupby('A')
In [72]: for name, group in grouped:
....: print(name)
....: print(group)
....:
bar
A B C D
1 bar one 0.254161 1.511763
3 bar three 0.215897 -0.990582
5 bar two -0.077118 1.211526
foo
A B C D
0 foo one -0.575247 1.346061
2 foo two -1.143704 1.627081
4 foo two 1.193555 -0.441652
6 foo one -0.408530 0.268520
7 foo three -0.862495 0.024580
在按多个键分组的情况下,组名将是一个元组。
In [73]: for name, group in df.groupby(['A', 'B']):
....: print(name)
....: print(group)
....:
('bar', 'one')
A B C D
1 bar one 0.254161 1.511763
('bar', 'three')
A B C D
3 bar three 0.215897 -0.990582
('bar', 'two')
A B C D
5 bar two -0.077118 1.211526
('foo', 'one')
A B C D
0 foo one -0.575247 1.346061
6 foo one -0.408530 0.268520
('foo', 'three')
A B C D
7 foo three -0.862495 0.02458
('foo', 'two')
A B C D
2 foo two -1.143704 1.627081
4 foo two 1.193555 -0.441652
有关“遍历组”的更多信息,请参阅 遍历组。
选择一个组#
可以使用 DataFrameGroupBy.get_group() 选择单个组。
In [74]: grouped.get_group("bar")
Out[74]:
A B C D
1 bar one 0.254161 1.511763
3 bar three 0.215897 -0.990582
5 bar two -0.077118 1.211526
或者对于按多个列分组的对象。
In [75]: df.groupby(["A", "B"]).get_group(("bar", "one"))
Out[75]:
A B C D
1 bar one 0.254161 1.511763
聚合#
聚合是一个 GroupBy 操作,它降低了分组对象的维度。聚合的结果是对组中每个列的标量值,或者至少被视为标量值。例如,生成一组值的和。
In [76]: animals = pd.DataFrame(
....: {
....: "kind": ["cat", "dog", "cat", "dog"],
....: "height": [9.1, 6.0, 9.5, 34.0],
....: "weight": [7.9, 7.5, 9.9, 198.0],
....: }
....: )
....:
In [77]: animals
Out[77]:
kind height weight
0 cat 9.1 7.9
1 dog 6.0 7.5
2 cat 9.5 9.9
3 dog 34.0 198.0
In [78]: animals.groupby("kind").sum()
Out[78]:
height weight
kind
cat 18.6 17.8
dog 40.0 205.5
在结果中,组的键默认出现在索引中。通过传递 as_index=False,它们也可以作为列包含在内。
In [79]: animals.groupby("kind", as_index=False).sum()
Out[79]:
kind height weight
0 cat 18.6 17.8
1 dog 40.0 205.5
内置聚合方法#
许多常见的聚合作为方法内置于 GroupBy 对象中。在下面列出的方法中,带有 * 的方法 *没有* 高效的、特定于 GroupBy 的实现。
方法 |
描述 |
|---|---|
计算组中的任何值是否为真。 |
|
计算组中的所有值是否为真。 |
|
计算组中非 NA 值的数量。 |
|
|
计算组的协方差。 |
计算每组中第一个出现的值。 |
|
计算每组中最大值的索引。 |
|
计算每组中最小值的索引。 |
|
计算每组中最后一个出现的值。 |
|
计算每组中的最大值。 |
|
计算每组的均值。 |
|
计算每组的中位数。 |
|
计算每组中的最小值。 |
|
计算每组中唯一值的数量。 |
|
计算每组值的乘积。 |
|
计算每组值的一个给定分位数。 |
|
计算每组值均值的标准误差。 |
|
计算每组中的值数量。 |
|
|
计算每组值的偏度。 |
计算每组值的标准差。 |
|
计算每组值的总和。 |
|
计算每组值的方差。 |
一些例子
In [80]: df.groupby("A")[["C", "D"]].max()
Out[80]:
C D
A
bar 0.254161 1.511763
foo 1.193555 1.627081
In [81]: df.groupby(["A", "B"]).mean()
Out[81]:
C D
A B
bar one 0.254161 1.511763
three 0.215897 -0.990582
two -0.077118 1.211526
foo one -0.491888 0.807291
three -0.862495 0.024580
two 0.024925 0.592714
另一个聚合的例子是计算每个组的大小。这在 GroupBy 中包含为 size 方法。它返回一个 Series,其索引由组名组成,值为每个组的大小。
In [82]: grouped = df.groupby(["A", "B"])
In [83]: grouped.size()
Out[83]:
A B
bar one 1
three 1
two 1
foo one 2
three 1
two 2
dtype: int64
虽然 DataFrameGroupBy.describe() 方法本身不是一个归约器,但它可以方便地生成关于每个组的摘要统计信息集合。
In [84]: grouped.describe()
Out[84]:
C ... D
count mean std ... 50% 75% max
A B ...
bar one 1.0 0.254161 NaN ... 1.511763 1.511763 1.511763
three 1.0 0.215897 NaN ... -0.990582 -0.990582 -0.990582
two 1.0 -0.077118 NaN ... 1.211526 1.211526 1.211526
foo one 2.0 -0.491888 0.117887 ... 0.807291 1.076676 1.346061
three 1.0 -0.862495 NaN ... 0.024580 0.024580 0.024580
two 2.0 0.024925 1.652692 ... 0.592714 1.109898 1.627081
[6 rows x 16 columns]
另一个聚合的例子是计算每个组的唯一值数量。这与 DataFrameGroupBy.value_counts() 函数类似,只是它只计算唯一值的数量。
In [85]: ll = [['foo', 1], ['foo', 2], ['foo', 2], ['bar', 1], ['bar', 1]]
In [86]: df4 = pd.DataFrame(ll, columns=["A", "B"])
In [87]: df4
Out[87]:
A B
0 foo 1
1 foo 2
2 foo 2
3 bar 1
4 bar 1
In [88]: df4.groupby("A")["B"].nunique()
Out[88]:
A
bar 1
foo 2
Name: B, dtype: int64
注意
当 as_index=True(默认值)时,聚合函数不会将你正在聚合的组作为命名的列返回。分组的列将是返回对象的索引。
传递 as_index=False将把聚合的组作为命名的列返回,无论它们在输入中是命名的索引还是列。
aggregate() 方法#
注意
aggregate() 方法可以接受多种不同类型的输入。本节详细介绍使用各种 GroupBy 方法的字符串别名;其他输入在下面的章节中详述。
pandas 实现的任何归约方法都可以作为字符串传递给 aggregate()。鼓励用户使用缩写 agg。它的作用相当于调用相应的方法。
In [89]: grouped = df.groupby("A")
In [90]: grouped[["C", "D"]].aggregate("sum")
Out[90]:
C D
A
bar 0.392940 1.732707
foo -1.796421 2.824590
In [91]: grouped = df.groupby(["A", "B"])
In [92]: grouped.agg("sum")
Out[92]:
C D
A B
bar one 0.254161 1.511763
three 0.215897 -0.990582
two -0.077118 1.211526
foo one -0.983776 1.614581
three -0.862495 0.024580
two 0.049851 1.185429
聚合的结果将以组名作为新索引。对于多个键,结果默认是一个 MultiIndex。如上所述,这可以通过使用 as_index 选项来更改。
In [93]: grouped = df.groupby(["A", "B"], as_index=False)
In [94]: grouped.agg("sum")
Out[94]:
A B C D
0 bar one 0.254161 1.511763
1 bar three 0.215897 -0.990582
2 bar two -0.077118 1.211526
3 foo one -0.983776 1.614581
4 foo three -0.862495 0.024580
5 foo two 0.049851 1.185429
In [95]: df.groupby("A", as_index=False)[["C", "D"]].agg("sum")
Out[95]:
A C D
0 bar 0.392940 1.732707
1 foo -1.796421 2.824590
请注意,你可以使用 DataFrame.reset_index() DataFrame 函数来达到与列名相同的效果,因为列名存储在结果的 MultiIndex 中,尽管这会额外复制一份。
In [96]: df.groupby(["A", "B"]).agg("sum").reset_index()
Out[96]:
A B C D
0 bar one 0.254161 1.511763
1 bar three 0.215897 -0.990582
2 bar two -0.077118 1.211526
3 foo one -0.983776 1.614581
4 foo three -0.862495 0.024580
5 foo two 0.049851 1.185429
使用用户定义函数进行聚合#
用户还可以提供自己的用户定义函数(UDFs)用于自定义聚合。
警告
使用 UDF 进行聚合时,UDF 不应修改提供的 Series。有关更多信息,请参阅 使用用户定义函数(UDF)方法进行修改。
注意
使用 UDF 进行聚合通常比使用 pandas 内置的 GroupBy 方法效率低。考虑将复杂操作分解为利用内置方法的链式操作。
In [97]: animals
Out[97]:
kind height weight
0 cat 9.1 7.9
1 dog 6.0 7.5
2 cat 9.5 9.9
3 dog 34.0 198.0
In [98]: animals.groupby("kind")[["height"]].agg(lambda x: set(x))
Out[98]:
height
kind
cat {9.1, 9.5}
dog {34.0, 6.0}
结果的数据类型将反映聚合函数的数据类型。如果不同组的结果具有不同的数据类型,则将以与 DataFrame 构建相同的方式确定一个通用数据类型。
In [99]: animals.groupby("kind")[["height"]].agg(lambda x: x.astype(int).sum())
Out[99]:
height
kind
cat 18
dog 40
一次应用多个函数#
在分组的 Series 上,你可以将函数列表或字典传递给 SeriesGroupBy.agg(),输出一个 DataFrame。
In [100]: grouped = df.groupby("A")
In [101]: grouped["C"].agg(["sum", "mean", "std"])
Out[101]:
sum mean std
A
bar 0.392940 0.130980 0.181231
foo -1.796421 -0.359284 0.912265
在分组的 DataFrame 上,你可以将函数列表传递给 DataFrameGroupBy.agg() 来聚合每个列,这会生成一个具有分层列索引的聚合结果。
In [102]: grouped[["C", "D"]].agg(["sum", "mean", "std"])
Out[102]:
C D
sum mean std sum mean std
A
bar 0.392940 0.130980 0.181231 1.732707 0.577569 1.366330
foo -1.796421 -0.359284 0.912265 2.824590 0.564918 0.884785
生成的聚合以函数本身命名。
对于 Series,如果你需要重命名,可以像这样进行链式操作。
In [103]: (
.....: grouped["C"]
.....: .agg(["sum", "mean", "std"])
.....: .rename(columns={"sum": "foo", "mean": "bar", "std": "baz"})
.....: )
.....:
Out[103]:
foo bar baz
A
bar 0.392940 0.130980 0.181231
foo -1.796421 -0.359284 0.912265
或者,你也可以简单地传递一个元组列表,每个元组包含新列名和聚合函数。
In [104]: (
.....: grouped["C"]
.....: .agg([("foo", "sum"), ("bar", "mean"), ("baz", "std")])
.....: )
.....:
Out[104]:
foo bar baz
A
bar 0.392940 0.130980 0.181231
foo -1.796421 -0.359284 0.912265
对于分组的 DataFrame,可以以类似的方式重命名。
通过链接 rename 操作。
In [105]: (
.....: grouped[["C", "D"]].agg(["sum", "mean", "std"]).rename(
.....: columns={"sum": "foo", "mean": "bar", "std": "baz"}
.....: )
.....: )
.....:
Out[105]:
C D
foo bar baz foo bar baz
A
bar 0.392940 0.130980 0.181231 1.732707 0.577569 1.366330
foo -1.796421 -0.359284 0.912265 2.824590 0.564918 0.884785
或者,传递一个元组列表。
In [106]: (
.....: grouped[["C", "D"]].agg(
.....: [("foo", "sum"), ("bar", "mean"), ("baz", "std")]
.....: )
.....: )
.....:
Out[106]:
C D
foo bar baz foo bar baz
A
bar 0.392940 0.130980 0.181231 1.732707 0.577569 1.366330
foo -1.796421 -0.359284 0.912265 2.824590 0.564918 0.884785
注意
通常,输出列名应该是唯一的,但 pandas 允许你对同一列应用相同的函数(或两个同名函数)。
In [107]: grouped["C"].agg(["sum", "sum"])
Out[107]:
sum sum
A
bar 0.392940 0.392940
foo -1.796421 -1.796421
pandas 还允许你提供多个 lambda 函数。在这种情况下,pandas 会“杂乱”地处理(无名称的)lambda 函数的名称,并在每个后续的 lambda 函数后附加 _<i>。
In [108]: grouped["C"].agg([lambda x: x.max() - x.min(), lambda x: x.median() - x.mean()])
Out[108]:
<lambda_0> <lambda_1>
A
bar 0.331279 0.084917
foo 2.337259 -0.215962
命名聚合#
为了支持列特定的聚合 *并控制输出列名*,pandas 在 DataFrameGroupBy.agg() 和 SeriesGroupBy.agg() 中接受一种特殊的语法,称为“命名聚合”,其中:
关键字是输出列名。
值是元组,其第一个元素是要选择的列,第二个元素是要应用于该列的聚合。pandas 提供了
NamedAgg命名元组,字段为['column', 'aggfunc'],以使其参数更清晰。像往常一样,聚合可以是可调用的或字符串别名。
In [109]: animals
Out[109]:
kind height weight
0 cat 9.1 7.9
1 dog 6.0 7.5
2 cat 9.5 9.9
3 dog 34.0 198.0
In [110]: animals.groupby("kind").agg(
.....: min_height=pd.NamedAgg(column="height", aggfunc="min"),
.....: max_height=pd.NamedAgg(column="height", aggfunc="max"),
.....: average_weight=pd.NamedAgg(column="weight", aggfunc="mean"),
.....: )
.....:
Out[110]:
min_height max_height average_weight
kind
cat 9.1 9.5 8.90
dog 6.0 34.0 102.75
NamedAgg 只是一个 namedtuple。也可以使用普通元组。
In [111]: animals.groupby("kind").agg(
.....: min_height=("height", "min"),
.....: max_height=("height", "max"),
.....: average_weight=("weight", "mean"),
.....: )
.....:
Out[111]:
min_height max_height average_weight
kind
cat 9.1 9.5 8.90
dog 6.0 34.0 102.75
如果你想要的列名不是有效的 Python 关键字,请构造一个字典并解包关键字参数。
In [112]: animals.groupby("kind").agg(
.....: **{
.....: "total weight": pd.NamedAgg(column="weight", aggfunc="sum")
.....: }
.....: )
.....:
Out[112]:
total weight
kind
cat 17.8
dog 205.5
使用命名聚合时,附加的关键字参数不会传递给聚合函数;只有 (column, aggfunc) 对才应作为 **kwargs 传递。如果你的聚合函数需要其他参数,请使用 functools.partial() 进行部分应用。
命名聚合对于 Series 的 groupby 聚合也有效。在这种情况下,没有列选择,所以值只是函数。
In [113]: animals.groupby("kind").height.agg(
.....: min_height="min",
.....: max_height="max",
.....: )
.....:
Out[113]:
min_height max_height
kind
cat 9.1 9.5
dog 6.0 34.0
对 DataFrame 列应用不同的函数#
通过将字典传递给 aggregate,你可以将不同的聚合应用于 DataFrame 的列。
In [114]: grouped.agg({"C": "sum", "D": lambda x: np.std(x, ddof=1)})
Out[114]:
C D
A
bar 0.392940 1.366330
foo -1.796421 0.884785
函数名也可以是字符串。为了使字符串有效,它必须在 GroupBy 上实现。
In [115]: grouped.agg({"C": "sum", "D": "std"})
Out[115]:
C D
A
bar 0.392940 1.366330
foo -1.796421 0.884785
转换#
转换是 GroupBy 操作,其结果的索引与被分组对象的索引相同。常见示例包括 cumsum() 和 diff()。
In [116]: speeds
Out[116]:
class order max_speed
falcon bird Falconiformes 389.0
parrot bird Psittaciformes 24.0
lion mammal Carnivora 80.2
monkey mammal Primates NaN
leopard mammal Carnivora 58.0
In [117]: grouped = speeds.groupby("class")["max_speed"]
In [118]: grouped.cumsum()
Out[118]:
falcon 389.0
parrot 413.0
lion 80.2
monkey NaN
leopard 138.2
Name: max_speed, dtype: float64
In [119]: grouped.diff()
Out[119]:
falcon NaN
parrot -365.0
lion NaN
monkey NaN
leopard NaN
Name: max_speed, dtype: float64
与聚合不同,用于拆分原始对象的组不会包含在结果中。
注意
由于转换不包括用于拆分结果的组,因此 DataFrame.groupby() 和 Series.groupby() 中的 as_index 和 sort 参数无效。
转换的一个常见用途是将结果添加回原始 DataFrame。
In [120]: result = speeds.copy()
In [121]: result["cumsum"] = grouped.cumsum()
In [122]: result["diff"] = grouped.diff()
In [123]: result
Out[123]:
class order max_speed cumsum diff
falcon bird Falconiformes 389.0 389.0 NaN
parrot bird Psittaciformes 24.0 413.0 -365.0
lion mammal Carnivora 80.2 80.2 NaN
monkey mammal Primates NaN NaN NaN
leopard mammal Carnivora 58.0 138.2 NaN
内置转换方法#
GroupBy 上的以下方法充当转换。
方法 |
描述 |
|---|---|
在每个组内回填 NA 值。 |
|
计算每个组内的累积计数。 |
|
计算每个组内的累积最大值。 |
|
计算每个组内的累积最小值。 |
|
计算每个组内的累积乘积。 |
|
计算每个组内的累积和。 |
|
计算组内相邻值之间的差值。 |
|
在每个组内向前填充 NA 值。 |
|
计算组内相邻值之间的百分比变化。 |
|
计算每个组内值的排名。 |
|
在组内将值向上或向下移动。 |
此外,将任何内置的聚合方法作为字符串传递给 transform()(参见下一节)会将结果广播到整个组,生成一个转换后的结果。如果聚合方法有高效的实现,这将也是高性能的。
transform() 方法#
与 聚合方法 类似,transform() 方法可以接受内置转换方法(上一节)的字符串别名。它也可以接受内置聚合方法的字符串别名。当提供聚合方法时,结果将被广播到整个组。
In [124]: speeds
Out[124]:
class order max_speed
falcon bird Falconiformes 389.0
parrot bird Psittaciformes 24.0
lion mammal Carnivora 80.2
monkey mammal Primates NaN
leopard mammal Carnivora 58.0
In [125]: grouped = speeds.groupby("class")[["max_speed"]]
In [126]: grouped.transform("cumsum")
Out[126]:
max_speed
falcon 389.0
parrot 413.0
lion 80.2
monkey NaN
leopard 138.2
In [127]: grouped.transform("sum")
Out[127]:
max_speed
falcon 413.0
parrot 413.0
lion 138.2
monkey 138.2
leopard 138.2
除了字符串别名之外,transform() 方法还可以接受用户定义函数(UDFs)。UDF 必须
返回一个大小与组块相同或可广播到组块大小的结果(例如,一个标量,
grouped.transform(lambda x: x.iloc[-1]))。按列对组块进行操作。转换应用于第一个组块,使用 chunk.apply。
不对组块执行原地操作。组块应被视为不可变的,对组块的更改可能会产生意外结果。有关更多信息,请参阅 使用用户定义函数(UDF)方法进行修改。
(可选)一次操作整个组块的所有列。如果支持此功能,则从第二个块开始使用快速路径。
注意
通过提供 UDF 来使用 transform 进行转换通常比使用 GroupBy 的内置方法效率低。考虑将复杂操作分解为利用内置方法的链式操作。
本节中的所有示例都可以通过调用内置方法而不是使用 UDF 来更高效地实现。请参阅下面的示例。
版本 2.0.0 中已更改: 当对分组的 DataFrame 使用 .transform 且转换函数返回 DataFrame 时,pandas 现在会将结果的索引与输入的索引对齐。你可以在转换函数中调用 .to_numpy() 来避免对齐。
与 The aggregate() method 类似,结果的数据类型将反映转换函数的数据类型。如果不同组的结果具有不同的数据类型,则将以与 DataFrame 构建相同的方式确定一个通用数据类型。
假设我们希望标准化每个组内的数据。
In [128]: index = pd.date_range("10/1/1999", periods=1100)
In [129]: ts = pd.Series(np.random.normal(0.5, 2, 1100), index)
In [130]: ts = ts.rolling(window=100, min_periods=100).mean().dropna()
In [131]: ts.head()
Out[131]:
2000-01-08 0.779333
2000-01-09 0.778852
2000-01-10 0.786476
2000-01-11 0.782797
2000-01-12 0.798110
Freq: D, dtype: float64
In [132]: ts.tail()
Out[132]:
2002-09-30 0.660294
2002-10-01 0.631095
2002-10-02 0.673601
2002-10-03 0.709213
2002-10-04 0.719369
Freq: D, dtype: float64
In [133]: transformed = ts.groupby(lambda x: x.year).transform(
.....: lambda x: (x - x.mean()) / x.std()
.....: )
.....:
我们可以预期结果现在在每个组内具有均值 0 和标准差 1( up to floating-point error),我们可以轻松地进行检查。
# Original Data
In [134]: grouped = ts.groupby(lambda x: x.year)
In [135]: grouped.mean()
Out[135]:
2000 0.442441
2001 0.526246
2002 0.459365
dtype: float64
In [136]: grouped.std()
Out[136]:
2000 0.131752
2001 0.210945
2002 0.128753
dtype: float64
# Transformed Data
In [137]: grouped_trans = transformed.groupby(lambda x: x.year)
In [138]: grouped_trans.mean()
Out[138]:
2000 -4.870756e-16
2001 -1.545187e-16
2002 4.136282e-16
dtype: float64
In [139]: grouped_trans.std()
Out[139]:
2000 1.0
2001 1.0
2002 1.0
dtype: float64
我们还可以直观地比较原始数据集和转换后的数据集。
In [140]: compare = pd.DataFrame({"Original": ts, "Transformed": transformed})
In [141]: compare.plot()
Out[141]: <Axes: >
输出维度较低的转换函数会被广播以匹配输入数组的形状。
In [142]: ts.groupby(lambda x: x.year).transform(lambda x: x.max() - x.min())
Out[142]:
2000-01-08 0.623893
2000-01-09 0.623893
2000-01-10 0.623893
2000-01-11 0.623893
2000-01-12 0.623893
...
2002-09-30 0.558275
2002-10-01 0.558275
2002-10-02 0.558275
2002-10-03 0.558275
2002-10-04 0.558275
Freq: D, Length: 1001, dtype: float64
另一个常见的数据转换是用组均值替换缺失数据。
In [143]: cols = ["A", "B", "C"]
In [144]: values = np.random.randn(1000, 3)
In [145]: values[np.random.randint(0, 1000, 100), 0] = np.nan
In [146]: values[np.random.randint(0, 1000, 50), 1] = np.nan
In [147]: values[np.random.randint(0, 1000, 200), 2] = np.nan
In [148]: data_df = pd.DataFrame(values, columns=cols)
In [149]: data_df
Out[149]:
A B C
0 1.539708 -1.166480 0.533026
1 1.302092 -0.505754 NaN
2 -0.371983 1.104803 -0.651520
3 -1.309622 1.118697 -1.161657
4 -1.924296 0.396437 0.812436
.. ... ... ...
995 -0.093110 0.683847 -0.774753
996 -0.185043 1.438572 NaN
997 -0.394469 -0.642343 0.011374
998 -1.174126 1.857148 NaN
999 0.234564 0.517098 0.393534
[1000 rows x 3 columns]
In [150]: countries = np.array(["US", "UK", "GR", "JP"])
In [151]: key = countries[np.random.randint(0, 4, 1000)]
In [152]: grouped = data_df.groupby(key)
# Non-NA count in each group
In [153]: grouped.count()
Out[153]:
A B C
GR 209 217 189
JP 240 255 217
UK 216 231 193
US 239 250 217
In [154]: transformed = grouped.transform(lambda x: x.fillna(x.mean()))
我们可以验证转换后的数据中组均值没有改变,并且转换后的数据不包含 NA。
In [155]: grouped_trans = transformed.groupby(key)
In [156]: grouped.mean() # original group means
Out[156]:
A B C
GR -0.098371 -0.015420 0.068053
JP 0.069025 0.023100 -0.077324
UK 0.034069 -0.052580 -0.116525
US 0.058664 -0.020399 0.028603
In [157]: grouped_trans.mean() # transformation did not change group means
Out[157]:
A B C
GR -0.098371 -0.015420 0.068053
JP 0.069025 0.023100 -0.077324
UK 0.034069 -0.052580 -0.116525
US 0.058664 -0.020399 0.028603
In [158]: grouped.count() # original has some missing data points
Out[158]:
A B C
GR 209 217 189
JP 240 255 217
UK 216 231 193
US 239 250 217
In [159]: grouped_trans.count() # counts after transformation
Out[159]:
A B C
GR 228 228 228
JP 267 267 267
UK 247 247 247
US 258 258 258
In [160]: grouped_trans.size() # Verify non-NA count equals group size
Out[160]:
GR 228
JP 267
UK 247
US 258
dtype: int64
如上面的注释所述,本节中的每个示例都可以使用内置方法更有效地计算。在下面的代码中,使用 UDF 的低效方法已注释掉,而更快的替代方法出现在下方。
# result = ts.groupby(lambda x: x.year).transform(
# lambda x: (x - x.mean()) / x.std()
# )
In [161]: grouped = ts.groupby(lambda x: x.year)
In [162]: result = (ts - grouped.transform("mean")) / grouped.transform("std")
# result = ts.groupby(lambda x: x.year).transform(lambda x: x.max() - x.min())
In [163]: grouped = ts.groupby(lambda x: x.year)
In [164]: result = grouped.transform("max") - grouped.transform("min")
# grouped = data_df.groupby(key)
# result = grouped.transform(lambda x: x.fillna(x.mean()))
In [165]: grouped = data_df.groupby(key)
In [166]: result = data_df.fillna(grouped.transform("mean"))
窗口和重采样操作#
可以在 GroupBy 上使用 resample()、expanding() 和 rolling() 作为方法。
下面的示例将在列 B 的样本上应用 rolling() 方法,基于列 A 的分组。
In [167]: df_re = pd.DataFrame({"A": [1] * 10 + [5] * 10, "B": np.arange(20)})
In [168]: df_re
Out[168]:
A B
0 1 0
1 1 1
2 1 2
3 1 3
4 1 4
.. .. ..
15 5 15
16 5 16
17 5 17
18 5 18
19 5 19
[20 rows x 2 columns]
In [169]: df_re.groupby("A").rolling(4).B.mean()
Out[169]:
A
1 0 NaN
1 NaN
2 NaN
3 1.5
4 2.5
...
5 15 13.5
16 14.5
17 15.5
18 16.5
19 17.5
Name: B, Length: 20, dtype: float64
expanding() 方法将对每个特定组的所有成员累积给定的操作(示例中为 sum())。
In [170]: df_re.groupby("A").expanding().sum()
Out[170]:
B
A
1 0 0.0
1 1.0
2 3.0
3 6.0
4 10.0
... ...
5 15 75.0
16 91.0
17 108.0
18 126.0
19 145.0
[20 rows x 1 columns]
假设您想使用 resample() 方法来获取数据帧中每个组的每日频率,并希望使用 ffill() 方法来填充缺失值。
In [171]: df_re = pd.DataFrame(
.....: {
.....: "date": pd.date_range(start="2016-01-01", periods=4, freq="W"),
.....: "group": [1, 1, 2, 2],
.....: "val": [5, 6, 7, 8],
.....: }
.....: ).set_index("date")
.....:
In [172]: df_re
Out[172]:
group val
date
2016-01-03 1 5
2016-01-10 1 6
2016-01-17 2 7
2016-01-24 2 8
In [173]: df_re.groupby("group").resample("1D").ffill()
Out[173]:
val
group date
1 2016-01-03 5
2016-01-04 5
2016-01-05 5
2016-01-06 5
2016-01-07 5
... ...
2 2016-01-20 7
2016-01-21 7
2016-01-22 7
2016-01-23 7
2016-01-24 8
[16 rows x 1 columns]
过滤#
过滤是一种 GroupBy 操作,用于对原始分组对象进行子集划分。它可以过滤掉整个组、组的一部分或两者都过滤。过滤返回调用对象的过滤版本,包括在提供时使用的分组列。在以下示例中,class 被包含在结果中。
In [174]: speeds
Out[174]:
class order max_speed
falcon bird Falconiformes 389.0
parrot bird Psittaciformes 24.0
lion mammal Carnivora 80.2
monkey mammal Primates NaN
leopard mammal Carnivora 58.0
In [175]: speeds.groupby("class").nth(1)
Out[175]:
class order max_speed
parrot bird Psittaciformes 24.0
monkey mammal Primates NaN
注意
与聚合不同,过滤不会将组键添加到结果的索引中。因此,传递 as_index=False 或 sort=True 不会影响这些方法。
过滤将尊重 GroupBy 对象列的子集划分。
In [176]: speeds.groupby("class")[["order", "max_speed"]].nth(1)
Out[176]:
order max_speed
parrot Psittaciformes 24.0
monkey Primates NaN
内置过滤#
GroupBy 上的以下方法充当过滤。所有这些方法都有一个高效的、特定于 GroupBy 的实现。
用户还可以使用转换以及布尔索引来构建组内的复杂过滤。例如,假设我们有一组产品及其销量,我们希望将数据子集化为仅占每个组总销量不超过 90% 的最大产品。
In [177]: product_volumes = pd.DataFrame(
.....: {
.....: "group": list("xxxxyyy"),
.....: "product": list("abcdefg"),
.....: "volume": [10, 30, 20, 15, 40, 10, 20],
.....: }
.....: )
.....:
In [178]: product_volumes
Out[178]:
group product volume
0 x a 10
1 x b 30
2 x c 20
3 x d 15
4 y e 40
5 y f 10
6 y g 20
# Sort by volume to select the largest products first
In [179]: product_volumes = product_volumes.sort_values("volume", ascending=False)
In [180]: grouped = product_volumes.groupby("group")["volume"]
In [181]: cumpct = grouped.cumsum() / grouped.transform("sum")
In [182]: cumpct
Out[182]:
4 0.571429
1 0.400000
2 0.666667
6 0.857143
3 0.866667
0 1.000000
5 1.000000
Name: volume, dtype: float64
In [183]: significant_products = product_volumes[cumpct <= 0.9]
In [184]: significant_products.sort_values(["group", "product"])
Out[184]:
group product volume
1 x b 30
2 x c 20
3 x d 15
4 y e 40
6 y g 20
filter 方法#
注意
通过提供 filter 和用户定义函数 (UDF) 来过滤通常不如使用 GroupBy 上的内置方法高效。考虑将复杂操作分解为利用内置方法的操作链。
filter 方法接受一个用户定义函数 (UDF),当应用于整个组时,该函数返回 True 或 False。然后 filter 方法的结果是 UDF 返回 True 的组的子集。
假设我们只想获取属于组总和大于 2 的组的元素。
In [185]: sf = pd.Series([1, 1, 2, 3, 3, 3])
In [186]: sf.groupby(sf).filter(lambda x: x.sum() > 2)
Out[186]:
3 3
4 3
5 3
dtype: int64
另一个有用的操作是过滤掉只包含少量成员的组的元素。
In [187]: dff = pd.DataFrame({"A": np.arange(8), "B": list("aabbbbcc")})
In [188]: dff.groupby("B").filter(lambda x: len(x) > 2)
Out[188]:
A B
2 2 b
3 3 b
4 4 b
5 5 b
或者,我们可以返回一个类似索引的对象,其中不符合过滤条件的组将被填充为 NaN,而不是删除不符合条件的组。
In [189]: dff.groupby("B").filter(lambda x: len(x) > 2, dropna=False)
Out[189]:
A B
0 NaN NaN
1 NaN NaN
2 2.0 b
3 3.0 b
4 4.0 b
5 5.0 b
6 NaN NaN
7 NaN NaN
对于具有多列的 DataFrame,过滤器应明确指定一列作为过滤条件。
In [190]: dff["C"] = np.arange(8)
In [191]: dff.groupby("B").filter(lambda x: len(x["C"]) > 2)
Out[191]:
A B C
2 2 b 2
3 3 b 3
4 4 b 4
5 5 b 5
灵活的 apply#
分组数据上的某些操作可能不属于聚合、转换或过滤类别。对于这些操作,您可以使用 apply 函数。
警告
apply 必须尝试从结果中推断它应该充当归约器、转换器或过滤器,具体取决于传递给它的内容。因此,分组列可能包含在输出中,也可能不包含。虽然它试图智能地猜测如何行为,但有时也会猜错。
注意
本节中的所有示例都可以使用其他 pandas 功能更可靠、更高效地计算。
In [192]: df
Out[192]:
A B C D
0 foo one -0.575247 1.346061
1 bar one 0.254161 1.511763
2 foo two -1.143704 1.627081
3 bar three 0.215897 -0.990582
4 foo two 1.193555 -0.441652
5 bar two -0.077118 1.211526
6 foo one -0.408530 0.268520
7 foo three -0.862495 0.024580
In [193]: grouped = df.groupby("A")
# could also just call .describe()
In [194]: grouped["C"].apply(lambda x: x.describe())
Out[194]:
A
bar count 3.000000
mean 0.130980
std 0.181231
min -0.077118
25% 0.069390
...
foo min -1.143704
25% -0.862495
50% -0.575247
75% -0.408530
max 1.193555
Name: C, Length: 16, dtype: float64
返回结果的维度也可以改变
In [195]: grouped = df.groupby('A')['C']
In [196]: def f(group):
.....: return pd.DataFrame({'original': group,
.....: 'demeaned': group - group.mean()})
.....:
In [197]: grouped.apply(f)
Out[197]:
original demeaned
A
bar 1 0.254161 0.123181
3 0.215897 0.084917
5 -0.077118 -0.208098
foo 0 -0.575247 -0.215962
2 -1.143704 -0.784420
4 1.193555 1.552839
6 -0.408530 -0.049245
7 -0.862495 -0.503211
apply 在 Series 上可以作用于函数返回的值,而该值本身是一个 Series,并可能将结果向上转换为 DataFrame。
In [198]: def f(x):
.....: return pd.Series([x, x ** 2], index=["x", "x^2"])
.....:
In [199]: s = pd.Series(np.random.rand(5))
In [200]: s
Out[200]:
0 0.582898
1 0.098352
2 0.001438
3 0.009420
4 0.815826
dtype: float64
In [201]: s.apply(f)
Out[201]:
x x^2
0 0.582898 0.339770
1 0.098352 0.009673
2 0.001438 0.000002
3 0.009420 0.000089
4 0.815826 0.665572
与 aggregate() 方法 类似,结果的 dtype 将反映应用函数的结果。如果不同组的结果具有不同的 dtype,则会以与 DataFrame 构造相同的方式确定公共 dtype。
使用 group_keys 控制分组列的位置#
要控制是否将分组列包含在索引中,可以使用参数 group_keys,该参数默认为 True。比较
In [202]: df.groupby("A", group_keys=True).apply(lambda x: x)
Out[202]:
B C D
A
bar 1 one 0.254161 1.511763
3 three 0.215897 -0.990582
5 two -0.077118 1.211526
foo 0 one -0.575247 1.346061
2 two -1.143704 1.627081
4 two 1.193555 -0.441652
6 one -0.408530 0.268520
7 three -0.862495 0.024580
与
In [203]: df.groupby("A", group_keys=False).apply(lambda x: x)
Out[203]:
B C D
0 one -0.575247 1.346061
1 one 0.254161 1.511763
2 two -1.143704 1.627081
3 three 0.215897 -0.990582
4 two 1.193555 -0.441652
5 two -0.077118 1.211526
6 one -0.408530 0.268520
7 three -0.862495 0.024580
Numba 加速例程#
如果 Numba 作为可选依赖项安装,则 transform 和 aggregate 方法支持 engine='numba' 和 engine_kwargs 参数。有关参数的一般用法和性能考虑因素,请参阅 使用 Numba 提高性能。
函数签名必须以 values, index **完全**开始,因为属于每个组的数据将被传递到 values,而组索引将被传递到 index。
警告
当使用 engine='numba' 时,内部将没有“回退”行为。组数据和组索引将作为 NumPy 数组传递给 JITed 用户定义的函数,不会尝试其他执行。
其他有用功能#
排除非数字列#
再次考虑我们一直在查看的示例 DataFrame。
In [204]: df
Out[204]:
A B C D
0 foo one -0.575247 1.346061
1 bar one 0.254161 1.511763
2 foo two -1.143704 1.627081
3 bar three 0.215897 -0.990582
4 foo two 1.193555 -0.441652
5 bar two -0.077118 1.211526
6 foo one -0.408530 0.268520
7 foo three -0.862495 0.024580
假设我们希望按 A 列计算标准差。有一个小问题,即我们不关心列 B 中的数据,因为它不是数字。您可以通过指定 numeric_only=True 来避免非数字列。
In [205]: df.groupby("A").std(numeric_only=True)
Out[205]:
C D
A
bar 0.181231 1.366330
foo 0.912265 0.884785
请注意,df.groupby('A').colname.std(). 比 df.groupby('A').std().colname 更有效。因此,如果聚合函数的结果仅在一个列(此处为 colname)上需要,则可以在应用聚合函数*之前*对其进行过滤。
In [206]: from decimal import Decimal
In [207]: df_dec = pd.DataFrame(
.....: {
.....: "id": [1, 2, 1, 2],
.....: "int_column": [1, 2, 3, 4],
.....: "dec_column": [
.....: Decimal("0.50"),
.....: Decimal("0.15"),
.....: Decimal("0.25"),
.....: Decimal("0.40"),
.....: ],
.....: }
.....: )
.....:
In [208]: df_dec.groupby(["id"])[["dec_column"]].sum()
Out[208]:
dec_column
id
1 0.75
2 0.55
处理(未观察到的)分类值#
当使用 Categorical 分组器(作为单个分组器或作为多个分组器的一部分)时,observed 关键字控制是返回所有可能的分组器值的笛卡尔积(observed=False)还是仅返回那些已被观察到的分组器(observed=True)。
显示所有值
In [209]: pd.Series([1, 1, 1]).groupby(
.....: pd.Categorical(["a", "a", "a"], categories=["a", "b"]), observed=False
.....: ).count()
.....:
Out[209]:
a 3
b 0
dtype: int64
仅显示观察到的值
In [210]: pd.Series([1, 1, 1]).groupby(
.....: pd.Categorical(["a", "a", "a"], categories=["a", "b"]), observed=True
.....: ).count()
.....:
Out[210]:
a 3
dtype: int64
分组后返回的 dtype 将*始终*包含所有被分组的类别。
In [211]: s = (
.....: pd.Series([1, 1, 1])
.....: .groupby(pd.Categorical(["a", "a", "a"], categories=["a", "b"]), observed=True)
.....: .count()
.....: )
.....:
In [212]: s.index.dtype
Out[212]: CategoricalDtype(categories=['a', 'b'], ordered=False, categories_dtype=str)
NA 组处理#
这里的 NA 指的是任何 NA 值,包括 NA、NaN、NaT 和 None。如果分组键中有任何 NA 值,默认情况下它们将被排除。换句话说,“NA 组”将被删除。您可以通过指定 dropna=False 来包含 NA 组。
In [213]: df = pd.DataFrame({"key": [1.0, 1.0, np.nan, 2.0, np.nan], "A": [1, 2, 3, 4, 5]})
In [214]: df
Out[214]:
key A
0 1.0 1
1 1.0 2
2 NaN 3
3 2.0 4
4 NaN 5
In [215]: df.groupby("key", dropna=True).sum()
Out[215]:
A
key
1.0 3
2.0 4
In [216]: df.groupby("key", dropna=False).sum()
Out[216]:
A
key
1.0 3
2.0 4
NaN 8
使用有序因子分组#
表示为 pandas Categorical 类实例的分类变量可用作组键。如果是这样,级别的顺序将被保留。当 observed=False 和 sort=False 时,任何未观察到的类别将按顺序出现在结果的末尾。
In [217]: days = pd.Categorical(
.....: values=["Wed", "Mon", "Thu", "Mon", "Wed", "Sat"],
.....: categories=["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
.....: )
.....:
In [218]: data = pd.DataFrame(
.....: {
.....: "day": days,
.....: "workers": [3, 4, 1, 4, 2, 2],
.....: }
.....: )
.....:
In [219]: data
Out[219]:
day workers
0 Wed 3
1 Mon 4
2 Thu 1
3 Mon 4
4 Wed 2
5 Sat 2
In [220]: data.groupby("day", observed=False, sort=True).sum()
Out[220]:
workers
day
Mon 8
Tue 0
Wed 5
Thu 1
Fri 0
Sat 2
Sun 0
In [221]: data.groupby("day", observed=False, sort=False).sum()
Out[221]:
workers
day
Wed 5
Mon 8
Thu 1
Sat 2
Tue 0
Fri 0
Sun 0
使用分组器规范分组#
您可能需要指定更多数据才能正确分组。您可以使用 pd.Grouper 来提供此本地控制。
In [222]: import datetime
In [223]: df = pd.DataFrame(
.....: {
.....: "Branch": "A A A A A A A B".split(),
.....: "Buyer": "Carl Mark Carl Carl Joe Joe Joe Carl".split(),
.....: "Quantity": [1, 3, 5, 1, 8, 1, 9, 3],
.....: "Date": [
.....: datetime.datetime(2013, 1, 1, 13, 0),
.....: datetime.datetime(2013, 1, 1, 13, 5),
.....: datetime.datetime(2013, 10, 1, 20, 0),
.....: datetime.datetime(2013, 10, 2, 10, 0),
.....: datetime.datetime(2013, 10, 1, 20, 0),
.....: datetime.datetime(2013, 10, 2, 10, 0),
.....: datetime.datetime(2013, 12, 2, 12, 0),
.....: datetime.datetime(2013, 12, 2, 14, 0),
.....: ],
.....: }
.....: )
.....:
In [224]: df
Out[224]:
Branch Buyer Quantity Date
0 A Carl 1 2013-01-01 13:00:00
1 A Mark 3 2013-01-01 13:05:00
2 A Carl 5 2013-10-01 20:00:00
3 A Carl 1 2013-10-02 10:00:00
4 A Joe 8 2013-10-01 20:00:00
5 A Joe 1 2013-10-02 10:00:00
6 A Joe 9 2013-12-02 12:00:00
7 B Carl 3 2013-12-02 14:00:00
按特定列按所需频率分组。这类似于重采样。
In [225]: df.groupby([pd.Grouper(freq="1ME", key="Date"), "Buyer"])[["Quantity"]].sum()
Out[225]:
Quantity
Date Buyer
2013-01-31 Carl 1
Mark 3
2013-10-31 Carl 6
Joe 9
2013-12-31 Carl 3
Joe 9
当指定了 freq 时,pd.Grouper 返回的对象将是 pandas.api.typing.TimeGrouper 的实例。当存在同名的列和索引时,您可以使用 key 按列分组,使用 level 按索引分组。
In [226]: df = df.set_index("Date")
In [227]: df["Date"] = df.index + pd.offsets.MonthEnd(2)
In [228]: df.groupby([pd.Grouper(freq="6ME", key="Date"), "Buyer"])[["Quantity"]].sum()
Out[228]:
Quantity
Date Buyer
2013-02-28 Carl 1
Mark 3
2014-02-28 Carl 9
Joe 18
In [229]: df.groupby([pd.Grouper(freq="6ME", level="Date"), "Buyer"])[["Quantity"]].sum()
Out[229]:
Quantity
Date Buyer
2013-01-31 Carl 1
Mark 3
2014-01-31 Carl 9
Joe 18
获取每个组的第一行#
与 DataFrame 或 Series 一样,您可以对 groupby 调用 head 和 tail。
In [230]: df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=["A", "B"])
In [231]: df
Out[231]:
A B
0 1 2
1 1 4
2 5 6
In [232]: g = df.groupby("A")
In [233]: g.head(1)
Out[233]:
A B
0 1 2
2 5 6
In [234]: g.tail(1)
Out[234]:
A B
1 1 4
2 5 6
这显示了每个组的前 n 行或最后 n 行。
获取每个组的第 n 行#
要选择每个组的第 n 项,请使用 DataFrameGroupBy.nth() 或 SeriesGroupBy.nth()。提供的参数可以是任何整数、整数列表、切片或切片列表;有关示例,请参见下文。当组的第 n 个元素不存在时,*不会*引发错误;而是不返回相应的行。
总的来说,此操作充当过滤。在某些情况下,它还将为每个组返回一行,使其也成为一个归约。但是,由于它通常可以返回零行或多行,因此 pandas 在所有情况下都将其视为过滤。
In [235]: df = pd.DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=["A", "B"])
In [236]: g = df.groupby("A")
In [237]: g.nth(0)
Out[237]:
A B
0 1 NaN
2 5 6.0
In [238]: g.nth(-1)
Out[238]:
A B
1 1 4.0
2 5 6.0
In [239]: g.nth(1)
Out[239]:
A B
1 1 4.0
如果组的第 n 个元素不存在,则结果中不包含相应的行。特别是,如果指定的 n 大于任何组,则结果将是一个空的 DataFrame。
In [240]: g.nth(5)
Out[240]:
Empty DataFrame
Columns: [A, B]
Index: []
如果您想选择第 n 个非空项,请使用 dropna 关键字参数。对于 DataFrame,这应该是 'any' 或 'all',就像您传递给 dropna 一样。
# nth(0) is the same as g.first()
In [241]: g.nth(0, dropna="any")
Out[241]:
A B
1 1 4.0
2 5 6.0
In [242]: g.first()
Out[242]:
B
A
1 4.0
5 6.0
# nth(-1) is the same as g.last()
In [243]: g.nth(-1, dropna="any")
Out[243]:
A B
1 1 4.0
2 5 6.0
In [244]: g.last()
Out[244]:
B
A
1 4.0
5 6.0
In [245]: g.B.nth(0, dropna="all")
Out[245]:
1 4.0
2 6.0
Name: B, dtype: float64
您还可以通过指定多个 nth 值(作为整数列表)来选择多个行。
In [246]: business_dates = pd.date_range(start="4/1/2014", end="6/30/2014", freq="B")
In [247]: df = pd.DataFrame(1, index=business_dates, columns=["a", "b"])
# get the first, 4th, and last date index for each month
In [248]: df.groupby([df.index.year, df.index.month]).nth([0, 3, -1])
Out[248]:
a b
2014-04-01 1 1
2014-04-04 1 1
2014-04-30 1 1
2014-05-01 1 1
2014-05-06 1 1
2014-05-30 1 1
2014-06-02 1 1
2014-06-05 1 1
2014-06-30 1 1
您还可以使用切片或切片列表。
In [249]: df.groupby([df.index.year, df.index.month]).nth[1:]
Out[249]:
a b
2014-04-02 1 1
2014-04-03 1 1
2014-04-04 1 1
2014-04-07 1 1
2014-04-08 1 1
... .. ..
2014-06-24 1 1
2014-06-25 1 1
2014-06-26 1 1
2014-06-27 1 1
2014-06-30 1 1
[62 rows x 2 columns]
In [250]: df.groupby([df.index.year, df.index.month]).nth[1:, :-1]
Out[250]:
a b
2014-04-01 1 1
2014-04-02 1 1
2014-04-03 1 1
2014-04-04 1 1
2014-04-07 1 1
... .. ..
2014-06-24 1 1
2014-06-25 1 1
2014-06-26 1 1
2014-06-27 1 1
2014-06-30 1 1
[65 rows x 2 columns]
枚举组项#
要查看每行在其组中的出现顺序,请使用 cumcount 方法。
In [251]: dfg = pd.DataFrame(list("aaabba"), columns=["A"])
In [252]: dfg
Out[252]:
A
0 a
1 a
2 a
3 b
4 b
5 a
In [253]: dfg.groupby("A").cumcount()
Out[253]:
0 0
1 1
2 2
3 0
4 1
5 3
dtype: int64
In [254]: dfg.groupby("A").cumcount(ascending=False)
Out[254]:
0 3
1 2
2 1
3 1
4 0
5 0
dtype: int64
枚举组#
要查看组的顺序(而不是 cumcount 提供的组内行的顺序),您可以使用 DataFrameGroupBy.ngroup()。
请注意,分配给组的数字与迭代 groupby 对象时看到的组的顺序相匹配,而不是它们首次出现的顺序。
In [255]: dfg = pd.DataFrame(list("aaabba"), columns=["A"])
In [256]: dfg
Out[256]:
A
0 a
1 a
2 a
3 b
4 b
5 a
In [257]: dfg.groupby("A").ngroup()
Out[257]:
0 0
1 0
2 0
3 1
4 1
5 0
dtype: int64
In [258]: dfg.groupby("A").ngroup(ascending=False)
Out[258]:
0 1
1 1
2 1
3 0
4 0
5 1
dtype: int64
绘图#
GroupBy 也适用于某些绘图方法。在这种情况下,假设我们怀疑列 1 中的值在组“B”中的平均值高 3 倍。
In [259]: np.random.seed(1234)
In [260]: df = pd.DataFrame(np.random.randn(50, 2))
In [261]: df["g"] = np.random.choice(["A", "B"], size=50)
In [262]: df.loc[df["g"] == "B", 1] += 3
我们可以轻松地用箱线图可视化这一点。
In [263]: df.groupby("g").boxplot()
Out[263]:
A Axes(0.1,0.15;0.363636x0.75)
B Axes(0.536364,0.15;0.363636x0.75)
dtype: object
调用 boxplot 的结果是一个字典,其键是我们分组列 g 的值(“A”和“B”)。结果字典的值可以通过 boxplot 的 return_type 关键字控制。有关更多信息,请参阅 可视化文档。
警告
出于历史原因,df.groupby("g").boxplot() 不等同于 df.boxplot(by="g")。有关解释,请参阅 此处。
管道函数调用#
与 DataFrame 和 Series 提供的功能类似,接受 GroupBy 对象的函数可以通过 pipe 方法链接在一起,以实现更清晰、更易读的语法。要了解有关 .pipe 的一般信息,请参阅 此处。
结合使用 .groupby 和 .pipe 通常在需要重用 GroupBy 对象时很有用。
例如,假设有一个包含商店、产品、收入和销量列的 DataFrame。我们想按商店和产品进行分组计算*价格*(即收入/销量)。我们可以通过多步操作来实现,但用管道方式表达可以使代码更具可读性。首先,我们设置数据。
In [264]: n = 1000
In [265]: df = pd.DataFrame(
.....: {
.....: "Store": np.random.choice(["Store_1", "Store_2"], n),
.....: "Product": np.random.choice(["Product_1", "Product_2"], n),
.....: "Revenue": (np.random.random(n) * 50 + 10).round(2),
.....: "Quantity": np.random.randint(1, 10, size=n),
.....: }
.....: )
.....:
In [266]: df.head(2)
Out[266]:
Store Product Revenue Quantity
0 Store_2 Product_1 26.12 1
1 Store_2 Product_1 28.86 1
现在我们按商店/产品查找价格。
In [267]: (
.....: df.groupby(["Store", "Product"])
.....: .pipe(lambda grp: grp.Revenue.sum() / grp.Quantity.sum())
.....: .unstack()
.....: .round(2)
.....: )
.....:
Out[267]:
Product Product_1 Product_2
Store
Store_1 6.82 7.05
Store_2 6.30 6.64
当您想将分组对象传递给任意函数时,管道也可以具有表现力,例如。
In [268]: def mean(groupby):
.....: return groupby.mean()
.....:
In [269]: df.groupby(["Store", "Product"]).pipe(mean)
Out[269]:
Revenue Quantity
Store Product
Store_1 Product_1 34.622727 5.075758
Product_2 35.482815 5.029630
Store_2 Product_1 32.972837 5.237589
Product_2 34.684360 5.224000
此处 mean 接受一个 GroupBy 对象,并分别找到每个商店-产品组合的 Revenue 和 Quantity 列的平均值。 mean 函数可以是任何接受 GroupBy 对象的函数; .pipe 将 GroupBy 对象作为参数传递给您指定的函数。
示例#
多列因子化#
通过使用 DataFrameGroupBy.ngroup(),我们可以提取关于组的信息,其方式类似于 factorize()(如 重塑 API 中所述),但它自然地应用于混合类型和不同来源的多列。这在处理的分类性中间步骤中可能很有用,当组行之间的关系比它们的内容更重要时,或者作为仅接受整数编码的算法的输入。(有关 pandas 对完整分类数据支持的更多信息,请参阅 分类介绍 和 API 文档。)
In [270]: dfg = pd.DataFrame({"A": [1, 1, 2, 3, 2], "B": list("aaaba")})
In [271]: dfg
Out[271]:
A B
0 1 a
1 1 a
2 2 a
3 3 b
4 2 a
In [272]: dfg.groupby(["A", "B"]).ngroup()
Out[272]:
0 0
1 0
2 1
3 2
4 1
dtype: int64
In [273]: dfg.groupby(["A", [0, 0, 0, 1, 1]]).ngroup()
Out[273]:
0 0
1 0
2 1
3 3
4 2
dtype: int64
按索引器进行 GroupBy 以“重采样”数据#
重采样会从已有的观测数据或生成数据的模型中产生新的假设样本(重采样)。这些新样本与预先存在的样本相似。
为了使重采样在非日期时间类索引上工作,可以使用以下过程。
在以下示例中,**df.index // 5** 返回一个整数数组,用于确定在 GroupBy 操作中选择哪些内容。
注意
下面的示例展示了如何通过合并样本来对样本进行降采样,使其成为更少的样本。这里通过使用 **df.index // 5**,我们将样本聚合到 bin 中。通过应用 **std()** 函数,我们将许多样本中的信息聚合到一小组值中,即它们的标准差,从而减少了样本数量。
In [274]: df = pd.DataFrame(np.random.randn(10, 2))
In [275]: df
Out[275]:
0 1
0 -0.793893 0.321153
1 0.342250 1.618906
2 -0.975807 1.918201
3 -0.810847 -1.405919
4 -1.977759 0.461659
5 0.730057 -1.316938
6 -0.751328 0.528290
7 -0.257759 -1.081009
8 0.505895 -1.701948
9 -1.006349 0.020208
In [276]: df.index // 5
Out[276]: Index([0, 0, 0, 0, 0, 1, 1, 1, 1, 1], dtype='int64')
In [277]: df.groupby(df.index // 5).std()
Out[277]:
0 1
0 0.823647 1.312912
1 0.760109 0.942941
返回 Series 以传播名称#
对 DataFrame 列进行分组,计算一组指标并返回一个命名 Series。Series 名称用作列索引的名称。这在与堆叠等重塑操作结合使用时特别有用,其中列索引名称将用作插入列的名称。
In [278]: df = pd.DataFrame(
.....: {
.....: "a": [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2],
.....: "b": [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1],
.....: "c": [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
.....: "d": [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1],
.....: }
.....: )
.....:
In [279]: def compute_metrics(x):
.....: result = {"b_sum": x["b"].sum(), "c_mean": x["c"].mean()}
.....: return pd.Series(result, name="metrics")
.....:
In [280]: result = df.groupby("a").apply(compute_metrics)
In [281]: result
Out[281]:
metrics b_sum c_mean
a
0 2.0 0.5
1 2.0 0.5
2 2.0 0.5
In [282]: result.stack()
Out[282]:
a metrics
0 b_sum 2.0
c_mean 0.5
1 b_sum 2.0
c_mean 0.5
2 b_sum 2.0
c_mean 0.5
dtype: float64