首頁  >  文章  >  後端開發  >  如何使用 Pandas GroupBy 取得字串並集?

如何使用 Pandas GroupBy 取得字串並集?

Patricia Arquette
Patricia Arquette原創
2024-10-26 09:50:03289瀏覽

How to Obtain a Union of Strings with Pandas GroupBy?

Pandas GroupBy:取得字串並集

在Pandas 中,groupby 函數提供了一個基於以下條件對資料進行分組的便捷方法:特定列並對結果組執行計算。但是,在處理字串列時,像 sum() 這樣的預設聚合函數可能不會總是產生所需的結果。

假設我們有一個包含「A」、「B」和「C」欄位的 DataFrame,其中「C」包含字串值。我們可以使用groupby("A")["C"].sum() 來取得每個群組的串聯字串:

<code class="python">print(df.groupby("A")["C"].sum())

# Output:
# A
# 1    Thisstring
# 2           is!
# 3             a
# 4        random
# Name: C, dtype: object</code>

取得字串的並集(即每組中的唯一字串)組),我們可以利用一個自訂函數來迭代“C”列的元素並創建一個用大括號括起來的逗號分隔字串。

<code class="python">def get_string_union(group):
    return "{%s}" % ', '.join(group['C'].unique())

df.groupby('A')['C'].apply(get_string_union)

# Output:
# A
# 1    {This, string}
# 2           {is, !}
# 3               {a}
# 4          {random}
# Name: C, dtype: object</code>

另一種方法涉及使用apply 函數和lambda 表達式:

<code class="python">df.groupby('A')['C'].apply(lambda x: "{%s}" % ', '.join(x))

# Output:
# A
# 1    {This, string}
# 2           {is, !}
# 3               {a}
# 4          {random}
# Name: C, dtype: object</code>

當應用於更大的DataFrame 時,可以利用自訂函數傳回包含每個組所需的字串並集的Series:

<code class="python">def f(x):
     return Series(dict(A = x['A'].sum(), 
                        B = x['B'].sum(), 
                        C = "{%s}" % ', '.join(x['C'])))

df.groupby('A').apply(f)

# Output:
#   A         B               C
# A                             
# 1  2  1.615586  {This, string}
# 2  4  0.421821         {is, !}
# 3  3  0.463468             {a}
# 4  4  0.643961        {random}</code>

透過利用自訂函數或帶有lambda 表達式的apply 函數,Pandas 允許我們從包含字串列的資料中操作並獲取特定結果。上述方法提供了方便的方法來組合每個群組中的唯一字串並以所需的格式傳回它們。

以上是如何使用 Pandas GroupBy 取得字串並集?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn