Skip to main content
 首页 » 编程设计

python之根据与其他 2 个列相关的条件创建一个列

2024年10月17日7kenshinobiy

我在 pandas DataFrame 中有两列(我们称之为“col1”和“col2”)。两者都包含 True/False 值。

我需要从这两列 ('col3') 创建第三列,如果两列中的一列或另一列在该记录中具有 True 值,则该记录将具有 True 值。

目前,我正在使用:

col3 = [] 
 
for index, row in df.iterrows(): 
    if df.ix[index, 'col1'] == True or df.ix[index, 'col2'] == True: 
        col3.append(True) 
    else: 
        col3.append(False) 
 
df['col3'] = col3 

对于我的数据集的大小,它的工作速度足够快,但是有没有办法以单行/矢量化的方式来完成它?也许使用两个嵌套的 np.where() 语句?

请您参考如下方法:

您可以使用 np.logical_or这样做:

In [236]: 
df = pd.DataFrame({'col1':[True,False,False], 'col2':[False,True,False]}) 
df 
 
Out[236]: 
    col1   col2 
0   True  False 
1  False   True 
2  False  False 
 
In [239]: 
df['col3'] = np.logical_or(df['col1'], df['col2']) 
df 
 
Out[239]: 
    col1   col2   col3 
0   True  False   True 
1  False   True   True 
2  False  False  False 

或者使用|操作符:

In [240]: 
df['col3'] = df['col1'] | df['col2'] 
 
df 
Out[240]: 
    col1   col2   col3 
0   True  False   True 
1  False   True   True 
2  False  False  False