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


Python pyspark register_dataframe_accessor用法及代碼示例

本文簡要介紹 pyspark.pandas.extensions.register_dataframe_accessor 的用法。

用法:

pyspark.pandas.extensions.register_dataframe_accessor(name: str) → Callable[[Type[T]], Type[T]]

使用 DataFrame 注冊自定義訪問器

參數

namestr

注冊後調用訪問者時使用的名稱

返回

可調用的

類裝飾器。

注意

訪問時,您的訪問器將使用用戶正在與之交互的pandas-on-Spark 對象進行初始化。訪問者的 init 方法應該總是攝取被訪問的對象。請參閱初始化簽名的示例。

在 pandas API 中,如果傳遞給您的訪問器的數據具有不正確的 dtype,建議提高 AttributeError 以保持一致性。在pandas-on-Spark 中,ValueError 更常用於在給定方法/函數的值的數據類型意外時進行注釋。

最終,您可以隨意構建它,但 pandas-on-Spark 可能會執行以下操作:

>>> ps.Series(['a', 'b']).dt
...
Traceback (most recent call last):
    ...
ValueError: Cannot call DatetimeMethods on type StringType

例子

在您的庫代碼中:

from pyspark.pandas.extensions import register_dataframe_accessor

@register_dataframe_accessor("geo")
class GeoAccessor:

    def __init__(self, pandas_on_spark_obj):
        self._obj = pandas_on_spark_obj
        # other constructor logic

    @property
    def center(self):
        # return the geographic center point of this DataFrame
        lat = self._obj.latitude
        lon = self._obj.longitude
        return (float(lon.mean()), float(lat.mean()))

    def plot(self):
        # plot this array's data on a map
        pass

然後,在 ipython 會話中:

>>> ## Import if the accessor is in the other file.
>>> # from my_ext_lib import GeoAccessor
>>> psdf = ps.DataFrame({"longitude": np.linspace(0,10),
...                     "latitude": np.linspace(0, 20)})
>>> psdf.geo.center  
(5.0, 10.0)

>>> psdf.geo.plot()

相關用法


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