如何在Pandas中创建与已有布尔列值相反的新布尔列
实现布尔列的反向取值并添加新列
原始DataFrame
| Column_1 | Column_2 | Column_3 | Column_4 | Column_5 | New_column |
|---|---|---|---|---|---|
| 82198 | True | False | False | red | True |
| 27498 | False | False | False | red | False |
| 84838 | False | False | True | red | True |
| 10498 | False | True | False | red | True |
解决方案
要生成与New_column值完全相反的New_column_2,利用Pandas对布尔列的直接取反操作即可,这里提供几种简洁的实现方式:
方法1:使用~运算符(最常用)
直接对布尔列取反,代码如下:
import pandas as pd # 构造原始数据 data = { 'Column_1': [82198, 27498, 84838, 10498], 'Column_2': [True, False, False, False], 'Column_3': [False, False, False, True], 'Column_4': [False, False, True, False], 'Column_5': ['red']*4, 'New_column': [True, False, True, True] } df = pd.DataFrame(data) # 添加反向列 df['New_column_2'] = ~df['New_column']
方法2:使用apply结合not
如果需要更显式的逻辑,可以用apply调用布尔取反:
df['New_column_2'] = df['New_column'].apply(lambda x: not x)
最终结果
执行上述代码后,得到的DataFrame如下:
| Column_1 | Column_2 | Column_3 | Column_4 | Column_5 | New_column | New_column_2 |
|---|---|---|---|---|---|---|
| 82198 | True | False | False | red | True | False |
| 27498 | False | False | False | red | False | True |
| 84838 | False | False | True | red | True | False |
| 10498 | False | True | False | red | True | False |
内容的提问来源于stack exchange,提问作者Carola
相关产品推荐
相关产品推荐

