首頁  >  文章  >  後端開發  >  如何建立一個新列,其中的值是根據現有的列選擇?

如何建立一個新列,其中的值是根據現有的列選擇?

王林
王林轉載
2024-02-22 13:40:13878瀏覽

如何建立一個新列,其中的值是根據現有的列選擇?

問題內容

如何將color 列新增到以下資料幀,以便color='green' 如果set == 'z',否則color='red'

Type  Set
1     A    Z
2     B    Z           
3     B    X
4     C    Y

正確答案


如果您只有兩個選擇,請使用np.where

df['color'] = np.where(df['set']=='z', 'green', 'red')

例如,

import pandas as pd
import numpy as np

df = pd.dataframe({'type':list('abbc'), 'set':list('zzxy')})
df['color'] = np.where(df['set']=='z', 'green', 'red')
print(df)

產量

set type  color
0   z    a  green
1   z    b  green
2   x    b    red
3   y    c    red

如果您有兩個以上的條件,請使用 np.select#。例如,如果您希望 color

  • yellow(df['set'] == 'z') & (df['type'] == 'a')
  • #否則 blue(df['set'] == 'z') & (df['type'] == 'b')
  • #否則 purple(df['type'] == 'b')
  • 否則 black

然後使用

df = pd.dataframe({'type':list('abbc'), 'set':list('zzxy')})
conditions = [
    (df['set'] == 'z') & (df['type'] == 'a'),
    (df['set'] == 'z') & (df['type'] == 'b'),
    (df['type'] == 'b')]
choices = ['yellow', 'blue', 'purple']
df['color'] = np.select(conditions, choices, default='black')
print(df)

產生

Set Type   color
0   Z    A  yellow
1   Z    B    blue
2   X    B  purple
3   Y    C   black

以上是如何建立一個新列,其中的值是根據現有的列選擇?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除