簡體   English   中英

基於條件在數據框中創建列

[英]Creating a Column in a Dataframe Based on a Conditional

我有一個數據框

pd.DataFrame({"A":[0,1,0,1],
          "B":[-1,0,0,0],
          "C":[0,0,0,0]},
         index = [.1,.2,.3, .4])

我首先在邏輯上解決問題的方式

for index, row in iterrows():
    if df['A'] == 1:
        df['C'] == 1
    elif df['B'] == -1
        df['C'] == -1
    else:
        df['C'] == 0

我想要

pd.DataFrame({"A":[0,1,0,1],
          "B":[-1,0,0,0],
          "C":[-1,1,0,1]},
         index = [.1,.2,.3, .4])

在嘗試了第一種方法之后,我嘗試了在其他問題中提出的多種方法,但似乎沒有一種適合我的問題。

使用numpy.select

df['C'] = pd.np.select([df.A == 1, df.B == -1], [1, -1])

df
#       A    B   C
#0.1    0   -1  -1
#0.2    1    0   1
#0.3    0    0   0
#0.4    1   -1   1

您可以使用嵌套的np.where調用:

df.C = np.where(df.A == 1, 1, np.where(df.B == -1, -1, 0))
df
     A  B  C
0.1  0 -1 -1
0.2  1  0  1
0.3  0  0  0
0.4  1  0  1

性能

df = pd.concat([df] * 100000)

%timeit np.select([df.A == 1, df.B == -1], [1, -1])
100 loops, best of 3: 5.25 ms per loop

%timeit np.where(df.A == 1, 1, np.where(df.B == -1, -1, 0))
100 loops, best of 3: 2.86 ms per loop

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM