簡體   English   中英

np.logical_and進行三個測試

[英]np.logical_and with three tests

我試圖根據三列(3個測試)中的值的測試和結果來更新數據框中的一列。

一些示例代碼:

df_test = pd.DataFrame([('?',2.0,1,0,0,0), (None,2.0,1,0,0,0), 
                        (None,2.0,0,0,0,0),(None,2.0,0,1,0,0), 
                        ('?',2.0,0,0,0,0)], columns=['a','b','c','d','e','f'])
df_test.head()

當我嘗試以下df_test['g'] = np.where(np.logical_and(df_test['a'] != 'None', df_test['c'] == 0, df_test['d'] == 0), True, False).astype(int)我收到錯誤TypeError: return arrays must be of ArrayType因此我嘗試以下操作:

df_test = pd.DataFrame([('?',2.0,1,0,0,0), (None,2.0,1,0,0,0), 
                        (None,2.0,0,0,0,0),(None,2.0,0,1,0,0), 
                        ('?',2.0,0,0,0,0)], columns=['a','b','c','d','e','f'])
df_test['g'] = np.where(np.logical_and(df_test['a'] != None, 
                                       np.logical_and(df_test['c'] == 0, 
                                                      df_test['d'] == 0)), 
                        True, False).astype(int)
df_test.head()

在第2行,我希望看到0,而在第4行顯示正確時,我看到的是1。 測試1(a)應該為False,而第二(c)和第三(d)測試應該為True,True。 False == True == True是False。

    a   b   c   d   e   f   g
0   ?   2.0 1   0   0   0   0
1   None    2.0 1   0   0   0   0
2   None    2.0 0   0   0   0   1
3   None    2.0 0   1   0   0   0
4   ?   2.0 0   0   0   0   1

我需要一種方法來評估3個測試,並將int返回true或false。

對於3個或更多條件,請使用np.logical_and.reduce並傳遞掩碼列表;

mask = np.logical_and.reduce([
        df_test['a'].notna(), df_test['c'].eq(0), df_test['d'].eq(0)])
df_test['g'] = mask.astype(int)

print(df_test)
      a    b  c  d  e  f  g
0     ?  2.0  1  0  0  0  0
1  None  2.0  1  0  0  0  0
2  None  2.0  0  0  0  0  0
3  None  2.0  0  1  0  0  0
4     ?  2.0  0  0  0  0  1

隨后的np.where在這里是多余的。

嘗試:

df_test ['htest'] =(df_test ['a']。isna()&(df_test ['c'] == 0)&(df_test ['d'] == 0))。astype(int)

df_test['htest' ] = (df_test['a'].notna() & (df_test['c'] == 0) &  (df_test['d'] == 0)).astype(int)

輸出:

      a    b  c  d  e  f  htest
0     ?  2.0  1  0  0  0      0
1  None  2.0  1  0  0  0      0
2  None  2.0  0  0  0  0      0
3  None  2.0  0  1  0  0      0
4     ?  2.0  0  0  0  0      1

暫無
暫無

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

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