Search code examples
if-statementdataframecomparisonsegment

Python If Else Segmentation 'Invalid Type Comparison' Error in Dataframe


I have a sample dataframe (df_merged_1) shown below:

enter image description here

The Revenue column is a float64 dtype. I want to create a new column called 'Revenue_Segment'. This is what I want the end result to look like:

enter image description here

Below is the code I used to segment:

if df_merged_1['Revenue'] >= 0 and df_merged_1['Revenue'] <= 2200:
    df_merged_1['AUM_Segment'] == 'test1'
else:
    df_merged_1['AUM_Segment'] == 'test0'

But the code is not working ... I get the following error:

TypeError: invalid type comparison

Any help is greatly appreciated!


Solution

  • Not elegant, but this is the only solution I can think of now:

    # Make a new list to add it later to your df
    rev_segment = []
    
    # Loop through the Revenue column
    for revenue in df_merged_1['Revenue']:
        if revenue >= 0 and revenue <= 2200:
            rev_segment.append('test1')
        else:
            rev_segment.append('test0')
    
    # Now append the list to a new column
    df_merged_1['Revenue_Segment'] = rev_segment