Create a column based on condition pertaining to 2 other columns

前端 未结 1 1458
心在旅途
心在旅途 2021-01-15 17:02

I have two columns in a pandas DataFrame (let\'s call the \'col1\' and col2\'). Both contain True/False values.

I need to create a third column from these two (\'co

相关标签:
1条回答
  • 2021-01-15 18:01

    You can use np.logical_or to do this:

    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
    

    or use | operator:

    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
    
    0 讨论(0)
提交回复
热议问题