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

Linda Hamilton
發布: 2024-10-20 06:48:29
原創
661 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!