首頁  >  文章  >  後端開發  >  如何在Pandas中GroupBy後選擇特定列中具有最小值的行?

如何在Pandas中GroupBy後選擇特定列中具有最小值的行?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-28 03:20:30336瀏覽

How to Select Rows with Minimum Value in a Specific Column After GroupBy in Pandas?

Pandas GroupBy 並選擇特定列中具有最小值的行

使用Pandas DataFrame 時,通常需要按某些列對資料進行分組並對這些列執行操作組。一個常見的操作是選擇特定列中具有最小值的行。

在本文中,我們將探索一種簡單而有效的方法來完成此任務,而無需借助 MultiIndex。

問題陳述:

給定一個包含A、B 和C 列的DataFrame,我們的目標是為A 列中的每個值選擇B 列中具有最小值的行。

原始資料框:

A B C
1 4 3
1 5 4
1 2 10
2 7 2
2 4 4
2 6 6

所需輸出:

A B C
1 2 10
2 4 4

解決方案:

解決這個問題的關鍵在於Pandas的idxmin()方法。此方法傳回每個組的指定列中具有最小值的行的索引。

使用groupby()和idxmin(),我們可以直接選擇我們想要的行:

<code class="python"># Group the DataFrame by column 'A'
grouped = df.groupby('A')

# Get the index of the rows with the minimum value in column 'B' for each group
min_idx = grouped.B.idxmin()

# Use the index to select the desired rows
result = df.loc[min_idx]</code>

輸出:

   A  B   C
2  1  2  10
4  2  4   4

這種方法可以有效地為A 中的每個群組選擇B 列中具有最小值的行,而不需要複雜的資料結構或中間步驟。

以上是如何在Pandas中GroupBy後選擇特定列中具有最小值的行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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