Home > OS >  How to create a new column with multiple values in python dataframe using for loop?
How to create a new column with multiple values in python dataframe using for loop?

Time:11-24

I want to create a function with a for loop that iterates through a small dataframe and adds a new column with different values depending on the conditions set.

I have tried the below, but it returns the output for my first if statement for all the rows (it prints 'Top Buyers' for every row):

def CustomerSegmentClassifier(df):
    
    for i, row in df.iterrows():
        if (df['Recency'] <= 200).any() or (df['Frequency'] >= 20).any():
            df.at[i,'Cluster Name'] = 'Top Buyers'
        elif (df['Recency'].between(201, 750)).any() or (df['Frequency'].between(5,19)).any():
            df.at[i,'Cluster Name'] = 'Casual Buyers'
        else:
            df.at[i,'Cluster Name'] = 'Churned Buyers'
    return df

output

  • Related