當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python pyspark GroupBy.apply用法及代碼示例

本文簡要介紹 pyspark.pandas.groupby.GroupBy.apply 的用法。

用法:

GroupBy.apply(func: Callable, *args: Any, **kwargs: Any) → Union[pyspark.pandas.frame.DataFrame, pyspark.pandas.series.Series]

逐組應用函數 func 並將結果組合在一起。

傳遞給 apply 的函數必須采用 DataFrame 作為其第一個參數並返回一個 DataFrame。然後apply 將負責將結果組合回單個數據幀。因此,apply 是一種高度靈活的分組方法。

雖然 apply 是一種非常靈活的方法,但它的缺點是使用它可能比使用更具體的方法(如 aggtransform )慢很多。 pandas-on-Spark 提供了廣泛的方法,這些方法比使用 apply 用於特定目的要快得多,因此在達到 apply 之前嘗試使用它們。

注意

此 API 執行該函數一次以推斷可能昂貴的類型,例如,在聚合或排序後創建數據集時。

為避免這種情況,請在 func 中指定返回類型,例如,如下所示:

>>> def pandas_div(x) -> ps.DataFrame[float, float]:
...     return x[['B', 'C']] / x[['B', 'C']]

如果指定返回類型,則輸出列名稱變為 c0, c1, c2 … cn 。這些名稱按位置映射到 func 中返回的 DataFrame 。

要指定列名,您可以使用 pandas 友好的樣式指定它們,如下所示:

>>> def pandas_div(x) -> ps.DataFrame["a": float, "b": float]:
...     return x[['B', 'C']] / x[['B', 'C']]
>>> pdf = pd.DataFrame({'B': [1.], 'C': [3.]})
>>> def plus_one(x) -> ps.DataFrame[zip(pdf.columns, pdf.dtypes)]:
...     return x[['B', 'C']] / x[['B', 'C']]

當給定函數注釋了返回類型時,GroupBy 對象的原始索引將丟失,並且默認索引將附加到結果中。請謹慎配置默認索引。另請參閱Default Index Type

注意

func 中的 DataFrame 實際上是 Pandas DataFrame 。因此,允許在此函數中使用任何 pandas API。

參數

func可調用的

一個可調用函數,將 DataFrame 作為其第一個參數,並返回一個數據幀。

*args

要傳遞給 func 的位置參數。

**kwargs

要傳遞給 func 的關鍵字參數。

返回

appliedDataFrame 或係列

例子

>>> df = ps.DataFrame({'A': 'a a b'.split(),
...                    'B': [1, 2, 3],
...                    'C': [4, 6, 5]}, columns=['A', 'B', 'C'])
>>> g = df.groupby('A')

請注意,g 有兩個組,ab。通過各種方式調用apply,可以得到不同的分組結果:

下麵傳遞給 apply 的函數采用 DataFrame 作為參數並返回 DataFrame。 apply 將每個組的結果組合到一個新的 DataFrame 中:

>>> def plus_min(x):
...     return x + x.min()
>>> g.apply(plus_min).sort_index()  
    A  B   C
0  aa  2   8
1  aa  3  10
2  bb  6  10
>>> g.apply(sum).sort_index()  
    A  B   C
A
a  aa  3  10
b   b  3   5
>>> g.apply(len).sort_index()  
A
a    2
b    1
dtype: int64

您可以指定類型提示並防止模式推斷以獲得更好的性能。

>>> def pandas_div(x) -> ps.DataFrame[float, float]:
...     return x[['B', 'C']] / x[['B', 'C']]
>>> g.apply(pandas_div).sort_index()  
    c0   c1
0  1.0  1.0
1  1.0  1.0
2  1.0  1.0

在係列的情況下,它的工作原理如下。

>>> def plus_max(x) -> ps.Series[np.int]:
...     return x + x.max()
>>> df.B.groupby(df.A).apply(plus_max).sort_index()  
0    6
1    3
2    4
Name: B, dtype: int64
>>> def plus_min(x):
...     return x + x.min()
>>> df.B.groupby(df.A).apply(plus_min).sort_index()
0    2
1    3
2    6
Name: B, dtype: int64

您還可以返回一個標量值作為組的聚合值:

>>> def plus_length(x) -> np.int:
...     return len(x)
>>> df.B.groupby(df.A).apply(plus_length).sort_index()  
0    1
1    2
Name: B, dtype: int64

函數的額外參數可以如下傳遞。

>>> def calculation(x, y, z) -> np.int:
...     return len(x) + y * z
>>> df.B.groupby(df.A).apply(calculation, 5, z=10).sort_index()  
0    51
1    52
Name: B, dtype: int64

相關用法


注:本文由純淨天空篩選整理自spark.apache.org大神的英文原創作品 pyspark.pandas.groupby.GroupBy.apply。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。