將 ai.classify 與 pandas 一起使用

這個 ai.classify 函式會根據你提供的標籤來分類每一筆輸入列。

備註

概觀

ai.classify 函式會擴充 pandas Series 類別。 若要將使用者提供的標籤指派給每個輸入資料列,請在 pandas DataFrame 的文字欄上呼叫函式。

函式會傳回 pandas Series,其中包含分類標籤,可儲存在新的 DataFrame 資料行中。

小提示

我們建議使用 ai.classify 函式搭配至少兩個輸入標籤。

語法

df["classification"] = df["input"].ai.classify("category1", "category2", "category3")

參數

名稱 Description
labels
為必填項目
一或多個 字串 ,代表要比對輸入文字值的分類標籤集。

退貨

函式會傳回一個 pandas Series,其中包含每個輸入文本行的分類標籤。 如果無法分類文字值,對應的標籤會 null。

Example

# This code uses AI. Always review output for mistakes.

df = pd.DataFrame([
        "This duvet, lovingly hand-crafted from all-natural fabric, is perfect for a good night's sleep.",
        "Tired of friends judging your baking? With these handy-dandy measuring cups, you'll create culinary delights.",
        "Enjoy this *BRAND NEW CAR!* A compact SUV perfect for the professional commuter!"
    ], columns=["descriptions"])

df["category"] = df['descriptions'].ai.classify("kitchen", "bedroom", "garage", "other")
display(df)

輸出:

具有「描述」和「類別」欄的資料框的螢幕擷取畫面。「類別」欄會列出每個描述的類別名稱。

多模態輸入

若要分類圖片、PDF 或文字檔案,請設定 column_type="path" 輸入欄位包含檔案路徑字串的條件。 關於支援的檔案類型與設定,請參見 「在 AI 函數中使用多模態輸入」。

# This code uses AI. Always review output for mistakes.

file_path_series = aifunc.list_file_paths("/lakehouse/default/Files")
custom_df = pd.DataFrame({"file_path": file_path_series})

custom_df["highest_degree"] = custom_df["file_path"].ai.classify(
    "Master", "PhD", "Bachelor", "Other",
)
display(custom_df)

備註

當你用 aifunc.list_file_paths() 來建立檔案路徑欄位時,回傳 yarl.URL 的物件會自動被偵測為檔案路徑。 你只需要在欄位包含純文字 URL 時指定column_type="path"。

你也可以用 aifunc.load 來將檔案匯入 DataFrame,然後分類檔案路徑欄位:

# This code uses AI. Always review output for mistakes.

df, schema = aifunc.load("/lakehouse/default/Files")
df["category"] = df["file_path"].ai.classify("Master", "PhD", "Bachelor", "Other")
display(df)

當你使用 aifunc.load時,檔案路徑欄位包含 yarl.URL 會自動偵測到的物件。 對於純字串 URL,設 column_type="path"為 。