New column in Pandas dataframe based on boolean conditions

前端 未结 2 437
不知归路
不知归路 2021-01-18 19:57

I\'d like to create a new column to a Pandas dataframe populated with True or False based on the other values in each specific row. My approach to solve this task was to app

相关标签:
2条回答
  • 2021-01-18 20:14

    You should work column-wise (vectorised, efficient) rather than row-wise (inefficient, Python loop):

    df1['ops_on'] = (df1['Feed'] > 10) & (df1['Pressure'] > 10) & (df1['Temp'] > 10)
    

    The & ("and") operator is applied to Boolean series element-wise. An arbitrary number of such conditions can be chained.


    Alternatively, for the special case where you are performing the same comparison multiple times:

    df1['ops_on'] = df1[['Feed', 'Pressure', 'Temp']].gt(10).all(1)
    
    0 讨论(0)
  • 2021-01-18 20:27

    In your current setup, just re-write your function like this:

    def ops_on(row):
        return (row['Feed'] > 10) & (row['Pressure'] > 10) & (row['Temp'] > 10)
    
    0 讨论(0)
提交回复
热议问题