2017-07-16 65 views
1

這是一個新的數據幀是數據幀的一個子集:創建使用兩列之間的差異在大熊貓

index id drug sentences  SS1 SS2 
1  2 lex  very bad  0  1 
2  3 gym  very nice  1  1 
3  7 effex hard   1  0 
4  8 cymba poor   1  1 

我想找到行時,SS1和SS2是不同的,然後創建一個新的數據幀基於此。輸出應該是這樣的:

index id drug sentences  SS1 SS2 
1  2 lex  very bad  0  1 
3  7 effex hard   1  0 

這是我的代碼:

df [['index','id', 'drug', 'sentences', 'SS1', 'SS2' ]] = np.where(df.SS1 != df.SS2) 

但它有以下錯誤:ValueError: Must have equal len keys and value when setting with an ndarray

什麼建議嗎?

+0

@開源已經給你一個工作選擇,但僅作參考,你得到了一個'ValueError',因爲'np.where(df.SS1!= df.SS2)'返回一個你評估的索引,否一個'DataFrame'。 – peterfields

+0

@peterfields謝謝你 – Mary

回答

5

一種方式可以是以下幾點:

df_new = df[df.SS1 != df.SS2] 
print(df_new) 

輸出:

index id drug sentences SS1 SS2 
0  1 2 lex very bad 0 1 
2  3 7 effex  hard 1 0 

使用where

df_new = df.where(df.SS1 != df.SS2).dropna() 
print(df_new)