Conditional Logic on Pandas DataFrame

后端 未结 4 566
遥遥无期
遥遥无期 2020-12-01 03:23

How to apply conditional logic to a Pandas DataFrame.

See DataFrame shown below,

   data desired_output
0     1          False
1     2          Fals         


        
4条回答
  •  暖寄归人
    2020-12-01 04:16

    In [1]: df
    Out[1]:
       data
    0     1
    1     2
    2     3
    3     4
    

    You want to apply a function that conditionally returns a value based on the selected dataframe column.

    In [2]: df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')
    Out[2]:
    0     true
    1     true
    2    false
    3    false
    Name: data
    

    You can then assign that returned column to a new column in your dataframe:

    In [3]: df['desired_output'] = df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')
    
    In [4]: df
    Out[4]:
       data desired_output
    0     1           true
    1     2           true
    2     3          false
    3     4          false
    

提交回复
热议问题