共用方式為


語意函式

本文說明語意函式,以及其如何協助數據科學家和數據工程師探索與所處理之 FabricDataFrame 或 FabricSeries 相關的函式。 語意函式是Microsoft網狀架構語意連結功能的一部分。

針對 Spark 3.4 和更新版本,語意連結核心套件可在預設 Fabric 運行時間中使用,但需要手動安裝包含語意函式邏輯的 is_holidaysemantic-link-functions 套件。 若要更新至最新版本的 Python 語意連結 (SemPy) 連結庫,請執行下列命令:

%pip install -U semantic-link

FabricDataFrame 會根據每個函式所定義的邏輯動態公開語意函式。 例如,當您處理同時包含 datetime 數據行和國家/地區數據行的 FabricDataFrame 時,函 is_holiday 式會出現在自動完成建議中。

每個語意函式都會使用 FabricDataFrame 或 FabricSeries 中有關數據、數據類型和元數據的資訊(例如 Power BI 數據類別),以判斷其與您所處理之特定數據的相關性。

使用 @semantic_function 裝飾項目標註時,會自動探索語意函式。 您可以將語意函式視為套 用至 DataFrame 概念的 C# 擴充方法

語意函式自動完成建議

當您使用 FabricDataFrame 或 FabricSeries 時,可以在自動完成建議中使用語意函式。 使用 Ctrl+空格鍵來觸發自動完成。

自動完成建議中語意函式的螢幕快照。

下列程式代碼範例會手動指定 FabricDataFrame 的元資料:

from sempy.fabric import FabricDataFrame

df = FabricDataFrame(
    {"country": ["US", "AT"],
        "lat": [40.7128, 47.8095],
        "long": [-74.0060, 13.0550]},
    column_metadata={"lat": {"data_category": "Latitude"}, "long": {"data_category": "Longitude"}},
)

# Convert to GeoPandas dataframe
df_geo = df.to_geopandas(lat_col="lat", long_col="long")

# Use the explore function to visualize the data
df_geo.explore()

或者,如果您從語意模型讀取到 FabricDataFrame,則會自動填入元數據。

from sempy.fabric import FabricDataFrame

# Read from semantic model
import sempy.fabric as fabric
df = fabric.read_table("my_dataset_name", "my_countries")

# Convert to GeoPandas dataframe
df_geo = df.to_geopandas(lat_col="lat", long_col="long")

# Use the explore function to visualize the data
df_geo.explore()

內建語意函式

SemPy Python 連結庫提供一組現成可用的內建語意函式。 這些內建函式包括:

自定義語意函式

語意函式是針對擴充性所設計。 您可以在筆記本內或個別的 Python 模組中定義自己的語意函式。

若要在筆記本外部使用語意函式,請在模組內 sempy.functions 宣告語意函式。 下列程式代碼範例示範如果城市是國家/地區之都,則會傳回true的語意函_is_capital式定義。

from sempy.fabric import FabricDataFrame, FabricSeries
from sempy.fabric.matcher import CountryMatcher, CityMatcher
from sempy.functions import semantic_function, semantic_parameters

@semantic_function("is_capital")
@semantic_parameters(col_country=CountryMatcher, col_city=CityMatcher)
def _is_capital(df: FabricDataFrame, col_country: str, col_city: str) -> FabricSeries:
    """Returns true if the city is the capital of the country"""
    capitals = {
        "US": ["Washington"],
        "AT": ["Vienna"],
        # ...
    }

    return df[[col_country, col_city]] \
        .apply(lambda row: row[1] in capitals[row[0]], axis=1)

在上述程式代碼範例中:

  • col_country 參數分別以 CountryMatchercol_cityCityMatcher加上批注。 此批注可讓語意函式在使用具有對應元數據的 FabricDataFrame 時自動探索。
  • 呼叫 函式也會提供標準數據類型,例如 strintfloatdatetime 來定義必要的輸入數據行。
  • 第一個參數 df 的類型批注會顯示函式適用於 FabricDataFrame,而不是 FabricSeries