Skip to main content
 首页 » 编程设计

python之使用 Pandas 中两列之间的差异创建一个新的数据框

2025年05月04日24www_RR

这是一个数据框的子集:

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

有什么建议吗?

请您参考如下方法:

一种方式可能如下:

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 

使用哪里:

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