首頁  >  文章  >  後端開發  >  如何在 Python 的 Pandas DataFrame 中執行條件列建立?

如何在 Python 的 Pandas DataFrame 中執行條件列建立?

Linda Hamilton
Linda Hamilton原創
2024-10-20 06:48:29663瀏覽

How to Perform Conditional Column Creation in Python's Pandas DataFrames?

在Python 中基於條件邏輯創建列

在使用Pandas DataFrame 時,我們經常遇到需要創建新列的場景基於現有列之間的條件檢查的列。這可以使用帶有嵌套條件的 np.where 函數來實現。

為了說明這一點,請考慮以下DataFrame:

<code class="python">import pandas as pd

df = pd.DataFrame({
    "A": [2, 3, 1],
    "B": [2, 1, 3]
})</code>

我們希望根據以下條件建立一個新欄位C :

  • 如果A 等於B,則C 應該為0。
  • 如果 A 大於 B,C 應該為 1。
  • 如果 A 小於 B ,C 應該是 -1。

使用自訂函數

一種方法是建立一個實作條件邏輯的自訂函數並將其應用於DataFrame:

<code class="python">def f(row):
    if row['A'] == row['B']:
        return 0
    elif row['A'] > row['B']:
        return 1
    else:
        return -1

df['C'] = df.apply(f, axis=1)</code>

使用np.where

或者,我們可以使用np.where 函數直接為新列賦值:

<code class="python">df['C'] = np.where(df['A'] == df['B'], 0, np.where(df['A'] > df['B'], 1, -1))</code>

這個方法是向量的,對於大型資料集更有效。

結果:

兩種方法都會產生以下結果:

<code class="python">print(df)

   A  B  C
0  2  2  0
1  3  1  1
2  1  3 -1</code>

以上是如何在 Python 的 Pandas DataFrame 中執行條件列建立?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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